save, update and remove data on the web | Firebase Realtime Database

Firebase frees developers to focus crafting fantastic user experiences. You don’t need to manage servers. You don’t need to write APIs. Firebase is your server, your API and your datastore, all written so generically that you can modify it to suit most needs.

Saving Data | Firebase Realtime Database

So let's imagine for example that we a page that has a text field (<input> or <textarea>..), and we want to save the data given by the user to our real-time database after clicking a send button:


This is what we get:

form example

Write data:

Now after creating your web project on console.firebase.google.com you're gonna get a configuration code, copy it and add it to your project.

There are  two methods to write data on:

a) Push method:



The results:

Firebase push method results

You can append data to a specific child by adding .child('ChildName') affter ref():

    var firebaseRef = firebase.database().ref().child("e-mails");

And you're going to get that instead:

Firebase push method results

The Push() method generates a unique key every time a new child is added to the specified Firebase reference. By using these auto-generated keys for each new element in the list, several clients can add children to the same location at the same time without write conflicts. The unique key generated by Push() is based on a timestamp, so list items are automatically ordered chronologically.

You can use the reference to the new data returned by the Push() method to get the value of the child's auto-generated key or set data for the child. Calling Key on a Push() reference returns the value of the auto-generated key.

    var key = firebaseRef.push(email).key

b) Set method:

Unlike push, set method gives you the ability to generate you own keys, for example:

    var firebaseRef = firebase.database().ref("emails")
    firebaseRef.set({email_1:"wadiemendja@gmail.com"})

set method firebase realtime database

c) Push and set a bunch of data:

1) With set():

    userID="wadiemendja"
    var data = {
        email:"wadiemendja@gmail.com",
        password:"PASSWORD"
    }
    var firebaseRef = firebase.database().ref("users/"+userID)
    firebaseRef.set(data)

2) With push():

    var data = {
        email:"wadiemendja@gmail.com",
        password:"PASSWORD"
    }
    var firebaseRef = firebase.database().ref("users")
    firebaseRef.push(data)


More details in the following video:


Update data:

    var key="wadiemendja"    
    var data = {
        email:"contact@wadiemendja.com",
        password:"anotherPASSWORD"
    }
    var firebaseRef = firebase.database().ref("users/"+key)
    firebaseRef.update(data)

update data firebase real time database

Remove data:

    var firebaseRef = firebase.database().ref("users/wadiemendja")
    firebaseRef.remove()

Read data:

A talked about it in another post with an example, see Here.

Post a Comment

1 Comments