Post navigation

A short introduction to Firebase

Firebase is a powerful API to store and sync data in realtime helping front-end developers build realtime apps for the web. You can save data, update data, and listen for data changes in realtime with only a few lines of code. Data is stored as standard JSON and is accessible from any platform. Firebase also has safety and security built in to keep your data and your users data safe.

Adding Firebase to the page

In order to use Firebase in your application you have to incluse the firebase js reference in the page header.

Using the JavaScript API

You can create new Firebase object in JavaScript quite easily then run many prebuilt functions and methods on that object for interacting with your data.

Adding Data:

// set up a new reference to your firebase appvarmyFirebaseRef=newFirebase("https://your-app-name.firebaseio.com/");

// use the .set() method to add data in the form of an objectmyFirebaseRef.set({name: "John"});
myFirebaseRef.set({comment: [{name: "Bob"},{name: "Dave"}]});

Running the set() method on your Firebase reference will allow you to setup new data. You need to be careful with your use of set as it wipes out all of the existing data and resets it for the node you’re referencing.

Updating Data:

Sometimes you don’t want to reset all the data in a node; actually most of the time you wont want to. For this, Firebase gives you the .update() method.

This code pushes a new node onto the comments node with a unique identifier. The push method and update method are what you’ll probably end up using the most when interacting with a web application.

Deleting Data:

You can also completely remove or delete data using the .remove() method. It’s use is pretty straightforward and you can target any reference point just like you would to set or update data.

// removes all data in your referencemyFirebaseRef.remove()
// removes all data in the child node of newsmyFirebaseRef.child('news').remove();

Pulling Data:

The .on() method is what sets up your data to be realtime, as it listens for data changes at a particular location. Your callback within the .on() method will be triggered for the initial data and again whenever the data changes.

The code above is getting a snapshot of all the data in our reference and logging the value of that data to the console with the .val() method. You can also run other methods on your snapshot including:.child().forEach().hasChild().hasChildren().ref()
* more listed here https://www.firebase.com/docs/web/api/datasnapshot/