← Back to Week 9

Firebase Databases

March 4, 2026 • Week 9

Topics Covered

Firebase Overview

Realtime Database

Data References

import { getDatabase, ref } from 'firebase/database';

const db = getDatabase();
const peopleRef = ref(db, "people");
const sarahRef = ref(db, "people/sarah");

Writing Data

import { ref, set as firebaseSet } from 'firebase/database';

// set() replaces the entire value
firebaseSet(sarahRef, 43)
  .then(() => console.log("saved!"))
  .catch(err => console.log(err));
import { ref, push as firebasePush } from 'firebase/database';

// push() auto-generates a unique key
firebasePush(taskRef, { description: 'First things first' });

Reading Data with Listeners

import { ref, onValue } from 'firebase/database';

const unregisterFunction = onValue(amitRef, (snapshot) => {
    const amitValue = snapshot.val();
});

Effect Hook Cleanup

useEffect(() => {
    const db = getDatabase();
    const amitRef = ref(db, "people/amit");

    const unregisterFunction = onValue(amitRef, (snapshot) => {
        const data = snapshot.val();
        // update state with data
    });

    // cleanup: disconnect listener on unmount
    return () => unregisterFunction();
}, []);

Firebase Arrays

// Convert Firebase object to array
const allTasksKeys = Object.keys(allTasksObject);
const allTasksArray = allTasksKeys.map((key) => {
    const task = { ...allTasksObject[key] };
    task.key = key;  // save key for later reference
    return task;
});

Updating Lecture Code

git checkout starter
git pull
git checkout main
git merge starter --no-edit

Key Concepts

Resources