Firebase Realtime Database is a NoSQL cloud database that allows you to store and sync data between your users in real-time. Here’s an example of how to read and write data using JavaScript:
To write data:
var database = firebase.database();function writeUserData(userId, name, email) { firebase.database().ref('users/' + userId).set({username: name,email: email });}
In this code snippet, we’re creating a reference to the ‘users’ node and setting the user’s details.
To read data:
var userId = firebase.auth().currentUser.uid;return firebase.database().ref('/users/' + userId).once('value').then(function(snapshot) { var username = (snapshot.val() && snapshot.val().username) || 'Anonymous';});
Here, we’re retrieving the current user’s data by their unique ID. The ‘once’ method triggers exactly once for the specified event type and then stops listening.