Simple Realtime Task List
Let’s create a simple task list 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 Task List</title>
</head>
<body>
<h1>Realtime Task List</h1>
<div id="task-list"></div>
<input type="text" id="task-input" placeholder="Enter a task">
<button onclick="addTask()">Add Task</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: "AIzaSyDmaZAcK7xwQTAsQJxaGnG56oB8RIJDMnc", authDomain: "samplep-d6b68.firebaseapp.com", projectId: "samplep-d6b68", storageBucket: "samplep-d6b68.appspot.com", messagingSenderId: "398502093281", appId: "1:398502093281:web:5d685b0733d4d6d66472a0", measurementId: "G-9E6K9YD8D1"};
// Initialize Firebase
firebase.initializeApp(firebaseConfig);
const database = firebase.database();
const taskList = document.getElementById('task-list');
function addTask() {
const task = document.getElementById('task-input').value;
const newTaskKey = firebase.database().ref().child('tasks').push().key;
const taskData = {
key: newTaskKey,
task: task
};
const updates = {};
updates['/tasks/' + newTaskKey] = taskData;
firebase.database().ref().update(updates);
document.getElementById('task-input').value = '';
}
database.ref('tasks/').on('value', (snapshot) => {
taskList.innerHTML = '';
snapshot.forEach((childSnapshot) => {
const childData = childSnapshot.val();
const taskElement = document.createElement('p');
taskElement.textContent = childData.task;
taskList.appendChild(taskElement);
});
});
</script>
</body>
</html>
Output:
Explanation:
- HTML Structure: The HTML file includes input fields for typing tasks and a button to add them to the task list.
- Initialize Firebase: Firebase is initialized with the configuration details.
- Adding Tasks: The addTask function pushes tasks to the tasks node in the database.
- Listening for Tasks: The on method listens for changes in the tasks node and updates the task list in real time.
Setting Up and Configuring Firebase Realtime Database
Firebase Realtime Database is a cloud-hosted NoSQL database that allows us to store and sync data between our users in real-time. It is a powerful tool for building applications that require live updates, such as chat apps, collaborative tools, and real-time analytics.
In this article, we will learn about the Firebase Realtime Database, the process of Setting Up Firebase Realtime Database and configuring the Firebase Realtime Database with detailed examples and outputs.
Contact Us