about syllabus All example source code
There are a few things to note when working with Firebase. Here are some steps to get you started.
Before you can start adding code, for my examples you’ll also need to make the data public. This is certainly a security issue and I would not recommend this for any projects that require private data. Navigate to the “RULES” tab in the firebase console and add the following:
Now you can go ahead and start adding code to work with Firebase. If you are working with a separate JS file for your code (like in my examples), make sure you add a reference to the firebase library in
The copy paste the initialize code and add to
setup() (or whatever event you are using for when the page is loaded):
You then need to create a “database” instance from the firebase object.
ref() function. So let’s say you want to store an inventory of fruit. You might create a path to “fruits”:
And then you can create an object with the data you want to save:
There are a variety of ways you can add data to Firebase, but in this case the easiest way is the
push() function. In other words, you want to push (aka “add”) a new fruit entry to the database.
This could be written as one line of code:
You can also get a callback.
You can then navigate to the firebase console to view the data.
The flip side of this is asking Firebase for data. An easy thing to do is assign a callback that returns all of the data for a specific reference (i.e. path).
The “value” event is triggered when changes are made to the database. You can then read all the data in a
gotData() callback (and see errors in a separate callback.) The
val() function returns an object with everything that lives as part of the “fruits” reference.
If you know the id of a specific fruit you could set a callback for just that one: