DEV Community

Ahmad Raza Khokhar
Ahmad Raza Khokhar

Posted on

How to perform Firebase CRUD Operations ?

Introduction

Firebase is famous set of backend that is used for Serverless or Headless web applications or mobile applications. In today’s topic, we will discuss how to perform complete CRUD operation in firebase. CRUD operation stands for Create, Read, Update and Delete and these are the major building blocks of any web app or mobile app.First of you will need to make a new project in firebase console Firebase Console after that, Lets start coding with the following steps:

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 the fields in firebase config file with the respective configuration given in your firebase console.

2. 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 we are using an example of books for our Firestore database collection. Remember that Firestore automatically creates the collection if the collection doesn’t exists in the database as Mongo DB does. Firestore is also a noSQL database which means it can also create the fields dynamically if those doesn’t exists in the document. noSQL databases scale vertically.

3. Get all documents from 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}`
      );
    }
  }

Enter fullscreen mode Exit fullscreen mode

4. Get 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

4. Delete firebase document by its id

//delete
  const deleteDocument = async (id) => {
    const booksCollection = collection(db, "books");
    const docRef = doc(booksCollection, id);
    await deleteDoc(docRef);
  };
Note: It is necessary to to give the collection reference in order to perform a successful operation. When dealing with single document, its ID is must that will be driven from the button the respective buttons are as 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 reading the article hope you found this helpful.

Regards,
Ahmad Raza Khokhar

Top comments (0)