
Cloud
Learning Level
Firebase Realtime Database is a NoSQL cloud database that syncs data in real-time across connected clients, perfect for collaborative applications and live updates.
By the end of this lesson, you'll understand:
{
"users": {
"user123": {
"email": "user@example.com",
"name": "John Doe",
"profile": {
"avatar": "url",
"bio": "..."
}
}
},
"posts": {
"post1": {
"title": "Hello Firebase",
"author": "user123",
"createdAt": 1234567890,
"likes": 5
}
}
}import { getDatabase, ref, set, push, update } from "firebase/database";
const database = getDatabase();
// Set data (overwrites)
await set(ref(database, 'users/user123'), {
email: 'user@example.com',
name: 'John Doe'
});
// Push (generates unique key)
const newPostRef = push(ref(database, 'posts'));
await set(newPostRef, {
title: 'My First Post',
author: 'user123',
createdAt: Date.now()
});
// Update (partial update)
await update(ref(database, 'posts/post1'), {
title: 'Updated Title',
updatedAt: Date.now()
});import { ref, get, onValue, query, orderByChild, limitToFirst } from "firebase/database";
// Read once
const snapshot = await get(ref(database, 'users/user123'));
if (snapshot.exists()) {
console.log(snapshot.val());
} else {
console.log('No data available');
}
// Real-time listener
const unsubscribe = onValue(ref(database, 'users'), (snapshot) => {
const users = snapshot.val();
console.log('Users:', users);
});
// Stop listening
unsubscribe();import { ref, query, orderByChild, limitToFirst, limitToLast, startAt, endAt } from "firebase/database";
// Order by child and limit
const q = query(
ref(database, 'posts'),
orderByChild('createdAt'),
limitToFirst(10)
);
const snapshot = await get(q);
snapshot.forEach(child => {
console.log(child.key, child.val());
});
// Range query
const rangeQuery = query(
ref(database, 'posts'),
orderByChild('likes'),
startAt(10),
endAt(100)
);import { ref, onValue, onChildAdded, onChildChanged, onChildRemoved } from "firebase/database";
// Listen for child changes
onChildAdded(ref(database, 'messages'), (snapshot) => {
console.log('New message:', snapshot.val());
});
onChildChanged(ref(database, 'messages'), (snapshot) => {
console.log('Message updated:', snapshot.val());
});
onChildRemoved(ref(database, 'messages'), (snapshot) => {
console.log('Message deleted:', snapshot.val());
});import { ref, set, onDisconnect, serverTimestamp } from "firebase/database";
// Mark user as online
const presenceRef = ref(database, 'presence/user123');
// Set online with cleanup on disconnect
await set(presenceRef, true);
onDisconnect(presenceRef).set(false);
// Check last seen
const statusRef = ref(database, 'status/user123');
await set(statusRef, {
state: 'online',
lastSeen: serverTimestamp()
});
onDisconnect(statusRef).update({
state: 'offline',
lastSeen: serverTimestamp()
});import { ref, push, set, query, limitToLast, onValue } from "firebase/database";
// Send message
async function sendMessage(roomId, userId, text) {
const messageRef = push(ref(database, `rooms/${roomId}/messages`));
await set(messageRef, {
author: userId,
text: text,
timestamp: Date.now()
});
}
// Listen to messages
function listenToMessages(roomId, callback) {
const q = query(
ref(database, `rooms/${roomId}/messages`),
limitToLast(50)
);
return onValue(q, (snapshot) => {
const messages = [];
snapshot.forEach(child => {
messages.push({
id: child.key,
...child.val()
});
});
callback(messages);
});
}import { useEffect, useState } from 'react';
import { ref, onValue } from "firebase/database";
import { db } from './firebase-config';
export function useRealtimeData(path) {
const [data, setData] = useState(null);
const [loading, setLoading] = useState(true);
useEffect(() => {
const unsubscribe = onValue(
ref(db, path),
(snapshot) => {
setData(snapshot.val());
setLoading(false);
},
(error) => {
console.error('Error:', error);
setLoading(false);
}
);
return () => unsubscribe();
}, [path]);
return { data, loading };
}
// Usage
export function ChatRoom({ roomId }) {
const { data: messages, loading } = useRealtimeData(`rooms/${roomId}/messages`);
if (loading) return <div>Loading...</div>;
return (
<div>
{messages && Object.entries(messages).map(([id, msg]) => (
<div key={id}>{msg.text}</div>
))}
</div>
);
}import { getDatabase, enableLogging } from "firebase/database";
// Enable offline persistence
const database = getDatabase();
// Offline persistence is enabled by default in web SDK
// Enable debug logging
enableLogging(true);
// Listen for connection state
import { ref, onValue } from "firebase/database";
onValue(ref(database, '.info/connected'), (snapshot) => {
if (snapshot.val() === true) {
console.log('Connected');
} else {
console.log('Disconnected');
}
});Explore Firebase Storage for file management, or implement advanced messaging patterns with Cloud Functions.
Resources
Ojasa Mirai
Master AI-powered development skills through structured learning, real projects, and verified credentials. Whether you're upskilling your team or launching your career, we deliver the skills companies actually need.
Learn Deep โข Build Real โข Verify Skills โข Launch Forward