How to save data to a firebase database (firestore) using firebase function using ReactJS

In Cloud Firestore, data is stored in collections. To add data to Firestore, import the Collection and addDoc functions. We also import the db initialized in the firebase.js file.

When the button is clicked, the Cloud Firestore creates a collection (we have named it todos) and adds data as a document to the todos collection.

For importing addDoc and Collection we first have to initialize the app in Firebase. For that, we have to import firestore from firebase using “getFirestore” and initialize it to the the app. Like show in the above image

Then We can import the “collection” and “addDoc” in the JavaScript file

For example

import { collection, addDoc } from "firebase/firestore";
import {database} from '../firebase';
   
    const addTodo = async (e) => {
        e.preventDefault();  
       
        try {
            const docRef = await addDoc(collection(db, "todos"), {
              todo: todo,    
            });
            console.log("Document written with ID: ", docRef.id);
          } catch (e) {
            console.error("Error adding document: ", e);
          }
    }

Leave a comment

Your email address will not be published. Required fields are marked *