DEV Community

M Ammar Ibne Saif
M Ammar Ibne Saif

Posted on

Mastering Firebase: A Comprehensive Guide to CRUD Operations

Firebase, a well-known backend platform, is widely utilized for building Serverless or Headless web and mobile applications. This discussion will delve into executing comprehensive CRUD (Create, Read, Update, Delete) operations within Firebase. CRUD operations serve as fundamental building blocks for both web and mobile applications. To initiate this process, create a new project in the Firebase Console. Subsequently, follow these steps for coding:

  1. Firebase configuration file setup
import { initializeApp } from "firebase/app";
// import { getAnalytics } from "firebase/analytics";
import { getFirestore } from "firebase/firestore";


const firebaseConfig = {
  apiKey: "API_KEY",
  authDomain: "AUTH_DOMAIN",
  projectId: "Project_ID",
  storageBucket: "Storage_Bucket",
  messagingSenderId: "Messaging_sender_ID",
  appId: "App_ID",
  measurementId: "Measurement_ID"
};
// Initialize Firebase
const app = initializeApp(firebaseConfig);


// const analytics = getAnalytics(app);
export const db = getFirestore(app);
Enter fullscreen mode Exit fullscreen mode

Note: Please replace all fields in the Firebase configuration file with the corresponding configuration values from your Firebase console.

  1. Add document to Firestore
import React, { useState } from "react";
import { dataBase } from "../FireBase/Firebase.config";
import { db } from "../FireBase/Firebase.config";
import {
  collection,
  addDoc,
  updateDoc,
  deleteDoc,
  getDoc,
  getDocs,
} from "firebase/firestore";
export default function AddBook() {
  const [bookName, setBookName] = useState("");
  const [price, setPrice] = useState("");
  const [currency, setCurrency] = useState("");

  async function addBook(e) {
    e.preventDefault();

    try {
        const booksCollection = collection(db, "books");
        const bookData = {bookName, price, currency}
      const querySnapshot = await addDoc(booksCollection, bookData);
      console.log(querySnapshot)
    } catch (error) {
      console.log(`There was an error in adding book: ${error}`);
    }
  }
  return (
    <div>
      <form onSubmit={addBook} className="addBookForm">
        <label htmlFor="book name">Book Name</label>
        <input
          type="text"
          name="book name"
          placeholder="Enter Book Name"
          onChange={(e) => setBookName(e.target.value)}
        />
        <label htmlFor="price">Price</label>
        <input
          type="text"
          name="price"
          placeholder="Enter Price"
          onChange={(e) => setPrice(e.target.value)}
        />
        <label htmlFor="currency">Currency</label>
        <input
          type="text"
          placeholder="USD, GBP, etc,."
          onChange={(e) => setCurrency(e.target.value)}
        />

        <input type="submit" value="Add Book" />
      </form>
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode

In this code snippet, we’re employing a book example to illustrate how to interact with a Firestore database collection. It’s important to note that Firestore automatically generates the collection if it doesn’t already exist in the database, similar to the behavior of MongoDB. Additionally, Firestore is a NoSQL database, meaning it can dynamically create fields within documents if they don’t already exist. NoSQL databases are known for their ability to scale vertically.

  1. Get all documents from the Firebase collection
//get all
  async function getCollection() {
    try {
      const booksCollection = collection(db, "books");
      const data = await getDocs(booksCollection);

      setBooksData(data.docs);
    } catch (error) {
      console.log(
        `There was an error fetching the data in firestore: ${error}`
      );
    }
  }
4. **Get the Document by ID and Update it**

 const[ selectedBook, setSelectedBook] = useState(null);
  //Get Document By ID
  const GetDocById = async (id) => {
    try {
      const booksCollection = collection(db, "books");
      const singleBook = doc(booksCollection, id);
      const response = await getDoc(singleBook);
      const data = response.data();
      setSelectedBook({data:data, id:id})
      setDisplay({display:'block'})
    } catch (error) {
      console.log(`Error in updateDocument: ${error}`)
    }

  };

//update form
 const setDocument = async(id)=>{
    try {
      const booksCollection = collection(db, 'books');
      const bookRef = doc(booksCollection, id);

      const selectedBook = {
        bookName,
        price,
        currency
      }
     await updateDoc(bookRef, selectedBook);
     setDisplay({display:'none'})
    } catch (error) {
      console.log(`Error in setDocument: ${error}`)
    }
  }

Enter fullscreen mode Exit fullscreen mode
  1. Delete the Firebase document by its id
//delete
  const deleteDocument = async (id) => {
    const booksCollection = collection(db, "books");
    const docRef = doc(booksCollection, id);
    await deleteDoc(docRef);
  };
Enter fullscreen mode Exit fullscreen mode

Note: Providing the collection reference is essential for executing operations successfully. When working with a single document, it’s imperative to have its corresponding ID, which will be derived from the associated button. The buttons required for these operations are outlined below:

         <button
                className="deleteDoc"
                onClick={() => {
                  deleteDocument(e.id);
                }}
              >
                Delete
              </button>
              <button
                className="updateDoc"
                onClick={() => {
                  updateDocument(e.id);
                }}
                onBlur={()=>setDisplay({display:'none'})}
              >
                Update
           </button>
Enter fullscreen mode Exit fullscreen mode

Thank you for taking the time to read the article. I hope you found it helpful and informative. If you have any further questions or need assistance, please feel free to ask.

Regards,
Muhammad Ammar Ibne Saif

Top comments (0)