Firebase FireStore (write ,read,query,update,delete)

share link

by bilal4 dot icon Updated: Nov 12, 2022

technology logo
technology logo

Guide Kit Guide Kit  

import React from "react";

import {

  getFirestore,

  collection,

  addDoc,

  getDoc,

  doc,

  query,

  where,

  getDocs,

  updateDoc,

  deleteField,

} from "firebase/firestore";

import { app } from "../Firebase/Firebase";

// import { async } from "@firebase/util";

// import { async } from "@firebase/util";

// import { async } from "@firebase/util";

// import { async } from "@firebase/util";


const FireStore = () => {

  const firestore = getFirestore(app);


  // Add documents to firestore

  const addDocument = async () => {

    try {

      const docRef = await addDoc(collection(firestore, "city"), {

        name: "Islamabad",

        parks: 3000,

        markets: 1815,

      });

      console.log("Document written with ID: ", docRef);

    } catch (e) {

      console.error("Error adding document: ", e);

    }

  };

  // Add document to firestore nested i4Wrq46K2FTz5WylqCmH


  const addsubDocument = async () => {

    try {

      const adddoc = await addDoc(

        collection(firestore, "users/i4Wrq46K2FTz5WylqCmH/fail"),

        {

          name: "Bilal Musa",

          FName: "Musa Khan",

        }

      );

      console.log(adddoc);

    } catch (e) {

      console.log(e);

    }

  };

  // Read Data from FireStore


  const readData = async () => {

    const dota = doc(firestore, "users", "bsez1fNn3vM6duo4FHFK");

    const snapShot = await getDoc(dota);

    console.log(snapShot.data());

  };


  // Read Data with Queries or on Some Conditions we need Data


  const readDataQuery = async () => {

    const collectionRef = collection(firestore, "users");

    const q = query(collectionRef, where("male", "==", true));

    let snapshot;

    snapshot = await getDocs(q); // Snapshot now become an array becouse of docs

    snapshot.forEach((data) => console.log(data.data()));

  };


  // Update Data in FireStore


  const updataData = async () => {

    const ref = doc(firestore, "users", "bsez1fNn3vM6duo4FHFK");

    const update = await updateDoc(ref, {

      last: deleteField(),

    });

    console.log(update);

  };


  return (

    <div>

      <h1>Firebase FireStore</h1>

      <button onClick={addDocument}>Add Data</button>

      <br />

      <hr />

      <button onClick={addsubDocument}>Add Sub Data</button>

      <br />

      <hr />

      <button onClick={readData}>Read Data </button>

      <br />

      <hr />

      <button onClick={readDataQuery}>Read Data through Query</button>

      <br />

      <hr />

      <button onClick={updataData}>Update Data</button>

    </div>

  );

};


export default FireStore;