Ojasa Mirai

Ojasa Mirai

Cloud

Loading...

Learning Level

๐ŸŸข Beginner๐Ÿ”ต Advanced
๐Ÿ”ง Firebase Project Setup๐Ÿ”‘ Firebase Authentication๐Ÿ” Firestore Security Rules๐Ÿ” Firestore Advanced Queriesโšก Realtime Database๐Ÿ“ Firebase Storageโšก Firebase Functions Advanced๐Ÿงช Firebase Emulator๐Ÿ“Š Firebase Analyticsโšก Firebase Performance๐Ÿ“ฌ Firebase Cloud Messaging๐Ÿš€ Firebase Hosting Advanced
Cloud/Firebase Integration/Realtime Database

โšก Realtime Database

Introduction

Firebase Realtime Database is a NoSQL cloud database that syncs data in real-time across connected clients, perfect for collaborative applications and live updates.

Key Learning Outcomes

By the end of this lesson, you'll understand:

  • Realtime Database structure and data types
  • Reading and writing data
  • Real-time listeners and synchronization
  • Offline persistence
  • Query capabilities
  • Security rules for Realtime Database
  • When to use Realtime vs Firestore

Database Structure

Hierarchical JSON Structure

{
  "users": {
    "user123": {
      "email": "user@example.com",
      "name": "John Doe",
      "profile": {
        "avatar": "url",
        "bio": "..."
      }
    }
  },
  "posts": {
    "post1": {
      "title": "Hello Firebase",
      "author": "user123",
      "createdAt": 1234567890,
      "likes": 5
    }
  }
}

Writing Data

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()
});

Reading Data

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();

Querying Data

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)
);

Real-Time Synchronization

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());
});

Presence Detection

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()
});

Realtime Chat Example

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);
  });
}

React Integration

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>
  );
}

Offline Persistence

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');
  }
});

Key Takeaways

  • **Realtime Database** provides instant data synchronization across clients
  • **Hierarchical structure** organizes data as nested JSON
  • **Real-time listeners** automatically update as data changes
  • **Queries** filter data by child values, order, and limits
  • **Presence detection** tracks online/offline status
  • **Offline persistence** enables functionality without connection
  • **Server timestamps** ensure consistent timing across clients
  • **Realtime Database** excels for collaborative and live features

Next Steps

Explore Firebase Storage for file management, or implement advanced messaging patterns with Cloud Functions.


Resources

Python Docs

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

Courses

PythonFastapiReactJSCloud

ยฉ 2026 Ojasa Mirai. All rights reserved.

TwitterGitHubLinkedIn