Efficient CRUD Operations in TypeScript with Firebase Firestore

Learn how to implement CRUD operations using TypeScript and Firebase Firestore. This guide provides code examples for creating, reading, updating, and deleting data.

Set up Firebase in your TypeScript project

npm install firebase @firebase/firestore

Firebase Configuration

import { initializeApp } from "firebase/app";
import { getFirestore } from "firebase/firestore";

// Firebase configuration
const firebaseConfig = {
  apiKey: "YOUR_API_KEY",
  authDomain: "YOUR_AUTH_DOMAIN",
  projectId: "YOUR_PROJECT_ID",
  storageBucket: "YOUR_STORAGE_BUCKET",
  messagingSenderId: "YOUR_MESSAGING_SENDER_ID",
  appId: "YOUR_APP_ID",
};

// Initialize Firebase
const app = initializeApp(firebaseConfig);

// Initialize Firestore
const db = getFirestore(app);

export { db };

Create (Add a Document)

import { collection, addDoc } from "firebase/firestore";
import { db } from "./firebase";

// Example function to add a document
async function addUser() {
  try {
    const docRef = await addDoc(collection(db, "users"), {
      name: "John Doe",
      email: "john.doe@example.com",
      age: 30,
    });
    console.log("Document written with ID: ", docRef.id);
  } catch (e) {
    console.error("Error adding document: ", e);
  }
}

addUser();

Read (Get Documents)

import { collection, getDocs } from "firebase/firestore";
import { db } from "./firebase";

// Example function to fetch documents
async function getUsers() {
  const querySnapshot = await getDocs(collection(db, "users"));
  querySnapshot.forEach((doc) => {
    console.log(`${doc.id} => `, doc.data());
  });
}

getUsers();

Update (Modify a Document)

import { doc, updateDoc } from "firebase/firestore";
import { db } from "./firebase";

// Example function to update a document
async function updateUser(userId: string) {
  const userRef = doc(db, "users", userId);

  try {
    await updateDoc(userRef, {
      name: "Jane Doe",
      age: 32,
    });
    console.log("Document successfully updated!");
  } catch (e) {
    console.error("Error updating document: ", e);
  }
}

updateUser("USER_DOCUMENT_ID");

Delete (Remove a Document)

import { doc, deleteDoc } from "firebase/firestore";
import { db } from "./firebase";

// Example function to delete a document
async function deleteUser(userId: string) {
  const userRef = doc(db, "users", userId);

  try {
    await deleteDoc(userRef);
    console.log("Document successfully deleted!");
  } catch (e) {
    console.error("Error deleting document: ", e);
  }
}

deleteUser("USER_DOCUMENT_ID");

Types: Since you’re using TypeScript, you can define types for your data to maintain type safety:

type User = {
  name: string;
  email: string;
  age: number;
};

Async/Await: All Firebase Firestore operations return promises, so it’s essential to handle them asynchronously.