Firebase Realtime Database: Reading and Writing Data

Firebase Realtime Database, a cloud-hosted NoSQL database developed by Google, provides a robust solution for achieving seamless real-time data updates across connected clients.

In this article, We will learn about the Firebase Realtime Database, How to Setting Up the Firebase Realtime Database, write data or read data to Firebase Realtime Database with an example of a Real-Time Simple Chat Application.

What is Firebase Realtime Database?

  • Firebase Realtime Database is a cloud-hosted NoSQL database provided by Firebase which is a platform developed by Google for creating mobile and web applications.
  • It enables real-time data synchronization across all clients connected to the database. When data changes, the connected clients receive updates immediately.
  • The database stores data as JSON (JavaScript Object Notation) objects which allows for a flexible and hierarchical data structure.
  • Firebase Realtime Database is known for its simple setup and ease of use also making it accessible for developers of varying skill levels.

Setting Up Firebase Realtime Database

Before we understanding the reading and writing data, let’s set up Firebase Realtime Database.

Step 1: Create a Firebase Project

  • Go to Firebase Console: Navigate to the Firebase Console.
  • Add a New Project: Click “Add project” and follow the setup instructions. Enter your project name, configure Google Analytics (if needed), and click “Create Project.”

Step 2: Add Firebase to Your App

Firebase provides guides for adding Firebase to various platforms. Here’s how to add Firebase to a web project:

Register Your App:

  • In the Firebase console, click the Web icon (</>) to register your web app.
  • Type a name for your app and then click on “Register app.”

Add Firebase SDK:

Firebase will provide a code snippet. Include this snippet in your HTML file.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>My Firebase App</title>
</head>
<body>
<h1>Welcome to Firebase Realtime Database</h1>
<script src="https://www.gstatic.com/firebasejs/9.6.4/firebase-app.js"></script>
<script src="https://www.gstatic.com/firebasejs/9.6.4/firebase-database.js"></script>
<script>
const firebaseConfig = {
apiKey: "YOUR_API_KEY",
authDomain: "YOUR_AUTH_DOMAIN",
databaseURL: "YOUR_DATABASE_URL",
projectId: "YOUR_PROJECT_ID",
storageBucket: "YOUR_STORAGE_BUCKET",
messagingSenderId: "YOUR_MESSAGING_SENDER_ID",
appId: "YOUR_APP_ID"
};

// Initialize Firebase
firebase.initializeApp(firebaseConfig);
</script>
</body>
</html>

Step 3: Enable Realtime Database

Go to Realtime Database:

  • Go to the Firebase Console and click on “Realtime Database” in the menu on the left side of the screen.

Create a Database:

  • Click “Create Database.”
  • Select your database location and choose a security rule. For development, you can start in “test mode,” which allows read and write access to your database.

Security Rules:

Let’s Set up our security rules to allow read and write access for testing. Make sure to update these rules before deploying your app to production.

{
"rules": {
".read": "auth != null",
".write": "auth != null"
}
}

Writing Data to Firebase Realtime Database

Writing Simple Data

To write data to Firebase Realtime Database, use the set method. Here’s an example of writing user data to the database:

function writeUserData(userId, name, email) {
firebase.database().ref('users/' + userId).set({
username: name,
email: email
});
}

// Example usage
writeUserData('1', 'John Doe', 'john.doe@example.com');

Explanation: The `writeUserData` function writes user data to the Firebase Realtime Database by creating or updating a user entry with the given `userId`, `name`, and `email` under the path `users/userId`. For example, calling `writeUserData(‘1’, ‘John Doe’, ‘john.doe@example.com’)` will store the username and email for the user with ID ‘1’.

Writing Data with Push

If we want Firebase to generate a unique key for each new child, use the push method. This is useful for lists of data, like messages or tasks.

function addMessage(userId, message) {
const messageRef = firebase.database().ref('messages/').push();
messageRef.set({
userId: userId,
message: message
});
}

// Example usage
addMessage('1', 'Hello, World!');

Output Example

After running the above code, our database structure will look like this:

{
"users": {
"1": {
"username": "John Doe",
"email": "john.doe@example.com"
}
},
"messages": {
"-Mabcd1234": {
"userId": "1",
"message": "Hello, World!"
}
}
}

Explanation:The `addMessage` function adds a new message to the Firebase Realtime Database by generating a unique key for each message and storing the `userId` and `message` under the path `messages/`. For example, calling `addMessage(‘1’, ‘Hello, World!’)` will add a new message from user ‘1’ with the content ‘Hello, World!’.

Reading Data from Firebase Realtime Database

Reading Data Once

To read data once from Firebase Realtime Database, use the once method. This is useful for fetching data without listening for changes.

function readUserData(userId) {
const userRef = firebase.database().ref('users/' + userId);
userRef.once('value').then((snapshot) => {
const data = snapshot.val();
console.log(data);
});
}

// Example usage
readUserData('1');

Explanation: The `readUserData` function reads user data from the Firebase Realtime Database by retrieving the data once for the given `userId` from the path `users/userId` and logging it to the console. For example, calling `readUserData(‘1’)` will fetch and log the data of the user with ID ‘1’.

Listening for Data Changes

To listen for real-time updates, use the on method. This will trigger every time the data at the specified reference changes.

function listenForUserData(userId) {
const userRef = firebase.database().ref('users/' + userId);
userRef.on('value', (snapshot) => {
const data = snapshot.val();
console.log(data);
});
}

// Example usage
listenForUserData('1');

Output

For the readUserData function, the console output will be:

{
"username": "John Doe",
"email": "john.doe@example.com"
}

Explanation: The `listenForUserData` function sets up a real-time listener on the Firebase Realtime Database to continuously monitor and log changes to the data of the user with the given `userId` from the path `users/userId`. For example, calling `listenForUserData(‘1’)` will log the data of the user with ID ‘1’ whenever it changes.

Updating Data

To update specific fields in our data without overwriting the entire node, use the update method:

function updateUserData(userId, email) {
const updates = {};
updates['/users/' + userId + '/email'] = email;

firebase.database().ref().update(updates);
}

// Example usage
updateUserData('1', 'new.email@example.com');

Output

After running the updateUserData function, the database will look like this:

{
"users": {
"1": {
"username": "John Doe",
"email": "new.email@example.com"
}
}
}

Deleting Data

To delete data from Firebase Realtime Database, use the remove method:

function deleteUser(userId) {
firebase.database().ref('users/' + userId).remove()
.then(() => {
console.log('User removed successfully.');
})
.catch((error) => {
console.error('Error removing user:', error);
});
}

// Example usage
deleteUser('1');

Output: After running the deleteUser function, the user data will be removed from the database.

Explanation: The `deleteUser` function removes the user data with the specified `userId` from the Firebase Realtime Database at the path `users/userId` and logs a success message or an error message if the removal fails. For example, calling `deleteUser(‘1’)` will delete the data for the user with ID ‘1’.

Example: Real-Time Simple Chat Application

Let’s create a simple real-time chat application to demonstrate Firebase Realtime Database in action.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Realtime Chat App</title>
</head>
<body>
<h1>Realtime Chat</h1>

<div id="chat-box"></div>
<input type="text" id="message" placeholder="Type a message">
<button onclick="sendMessage()">Send</button>

<script src="https://www.gstatic.com/firebasejs/9.6.4/firebase-app.js"></script>
<script src="https://www.gstatic.com/firebasejs/9.6.4/firebase-database.js"></script>
<script>
const firebaseConfig = {
apiKey: "YOUR_API_KEY",
authDomain: "YOUR_AUTH_DOMAIN",
databaseURL: "YOUR_DATABASE_URL",
projectId: "YOUR_PROJECT_ID",
storageBucket: "YOUR_STORAGE_BUCKET",
messagingSenderId: "YOUR_MESSAGING_SENDER_ID",
appId: "YOUR_APP_ID"
};

// Initialize Firebase
firebase.initializeApp(firebaseConfig);

const database = firebase.database();

const chatBox = document.getElementById('chat-box');

function sendMessage() {
const message = document.getElementById('message').value;
database.ref('messages/').push({
message: message,
timestamp: firebase.database.ServerValue.TIMESTAMP
});
document.getElementById('message').value = '';
}

database.ref('messages/').on('value', (snapshot) => {
chatBox.innerHTML = '';
snapshot.forEach((childSnapshot) => {
const childData = childSnapshot.val();
const messageElement = document.createElement('p');
messageElement.textContent = childData.message;
chatBox.appendChild(messageElement);
});
});
</script>
</body>
</html>

Output:

Explanation:

  • HTML Structure: The HTML file includes input fields for typing messages and a button to send them.
  • Initialize Firebase: Firebase is initialized with the configuration details.
  • Sending Messages: The sendMessage function pushes messages to the messages node in the database.
  • Listening for Messages: The on method listens for changes in the messages node and updates the chat box in real time.

Conclusion

Overall, By following the steps outlined in this guide, developers can effectively initialize Firebase, manage data through write and read operations, and implement real-time data updates to create engaging user experiences. Whether you are building a chat application, a collaborative tool, or a real-time analytics dashboard, Firebase Realtime Database provides the essential infrastructure to achieve your development goals efficiently.



Contact Us