DEV Community

Cover image for CRUD using Firebase In React
Simran Birla
Simran Birla

Posted on

CRUD using Firebase In React

This post will show you how to perform CRUD operations in react using a DaaS Firebase. You can perform a lot of functions once you know how to use firebase with React.

While making projects in FrontEnd, I always had the questions where should I keep the data and make the project in a way that a lot of people can see the data shared by other people.So then I thought of using firebase with React, which made the project complex in functionality but not in developing.

Setting up Firebase:

  1. Created a firebase account and create a web project in it.
  2. Install firebase tools: npm install -g firebase-tools npm install firebase
  3. Copy your config data from firebase
const firebaseApp = firebase.initializeApp({
  apiKey: "******************d4",
  authDomain: "***********.firebaseapp.com",
  databaseURL: "*********.firebaseio.com",
  projectId: "*******************",
  storageBucket: "************.appspot.com",
  messagingSenderId: "********************",
  appId: "*************:web:***********4",
  measurementId: "G-************",
});
Enter fullscreen mode Exit fullscreen mode
  1. In your React app create a file firebase.js in src directory
  2. Add the below code .
import firebase from "firebase";

const firebaseApp = firebase.initializeApp({
  apiKey: "AIzaSyBI_AQ3C2mXWKG1i-Amtzn97zfGVSDzWd4",
  authDomain: "pin-clone-39acf.firebaseapp.com",
  databaseURL: "https://pin-clone-39acf.firebaseio.com",
  projectId: "pin-clone-39acf",
  storageBucket: "pin-clone-39acf.appspot.com",
  messagingSenderId: "884413487053",
  appId: "1:884413487053:web:5a72dde51157b87b2ed684",
  measurementId: "G-VVCRZNMW6B",
});

const db = firebase.firestore();
const auth = firebase.auth();
const provider = new firebase.auth.GoogleAuthProvider();
const storage = firebase.storage();

export { db, storage, auth, provider };
Enter fullscreen mode Exit fullscreen mode

It will initialize firebase with your configuration.
firestore(): Then we create the firestore() which is the database we will use
auth(): is used to initialize the authorization in firebase
provider(): This is used to initialize the google authorization in the project, you can also use facebook, twitter authorization.
You have to enable authorization through firebase console
storage(): Used to store information from your project to firebase databse

Authorization:

For sign in :

auth.signInWithPopup(provider)
      .then((res) => {
        console.log("SIGN IN");
      })
      .catch((err) => alert(err));
Enter fullscreen mode Exit fullscreen mode

For sign out:

auth.signOut()
      .then((res) => {
        console.log(res);
       })
      .catch((err) => alert(err));
Enter fullscreen mode Exit fullscreen mode

Create:

Storage

So I used the storage for uploading an image and then acquiring the image link.We can do this with any file type.

You have to create a storage using firebase console

  1. Go to storage
  2. Create a new folder

firebase storage

const upload = storage.ref(`/<name of folder>/<name of file>`).put(<file>);
Enter fullscreen mode Exit fullscreen mode

The above code then adds the file into firebase storage

To get the download URL:

  upload.on(
    "state_changed",
    (snap) => {
      const progress = Math.round(
        (snap.bytesTransferred / snap.totalBytes) * 100
      );
      console.log(progress)
    },
    (error) => {
      alert(error.message);
    },
    () => {
      storage
        .ref(<name of folder>)
        .child(<name of file>)
        .getDownloadURL()
        .then((url) => {
          console.log(url)
        });
    }
  );
Enter fullscreen mode Exit fullscreen mode

When the state is changed ("state change")( whether the file has been uploaded successfully or not), The on() functions takes 2 functions.
The first tells us about the file uploading stage and the second one is used when file is uploaded.
If you want to see how much percent of upload is completed ,progress variable tells us that.

Once uploaded the second callback function, takes the storage variable defined in firebase file, maps down the path to get the url of the file

Database:

This is done when you want to add a document in firebase collection.

import { storage, db } from "../firebase";
import firebase from "firebase";

  db.collection("feed").add({
    name: "Hello",
    time: firebase.firestore.FieldValue.serverTimestamp(),
    userName: "helloworld",
   });

Enter fullscreen mode Exit fullscreen mode

You must remember to have the correct path in collection().

When you want to add a field in document then you can use the set method but remember you have to implement your whole document structure as it will overwrite everything.

Here you should know the id of the document.

db.collection("feed")
    .doc(id)
    .set({
      name: "heelo",
      username: "byeworld"
      url: "google.com"
    });
Enter fullscreen mode Exit fullscreen mode

Update:

When you want to change a field without overwriting the entire structure you use update()

db.collection("feed")
    .doc(id)
    .update({
      name: "hello",
    });
Enter fullscreen mode Exit fullscreen mode

This will update the value of name and every other field will remain the same.

Read:

To read data, you could use
1.get()
2.snapshot()

1.get():

db.collection("feed")
    .doc(id)
    .get()
    .then(info =>{
     if (info.exists) {
        console.log("Document data:", info.data());
    } else {
    // info.data() will be undefined in this case
        console.log("No such document!");
    }
    });
Enter fullscreen mode Exit fullscreen mode

2.snapshot():
The difference between snapshot() and get() is that, get() gives the data once whereas snapshot gets the data as soon as new data is added so it is recommended that you use snapshot() with useEffect()

db.collection(`boards/${props.auth.user.uid}/photos`).onSnapshot(
    (snap) => {
       setBoard(
          snap.docs.map((doc) => ({
          id: doc.id,
          photos: doc.data(),
         }))
      );
   }
);
Enter fullscreen mode Exit fullscreen mode

Delete:

db.collection(`feeds`)
  .doc(id)
  .delete()
  .then(() => {
     alert("Deleted!!");
   })
   .catch((err) => alert(err));
Enter fullscreen mode Exit fullscreen mode

As you can see by using firebase as a database for your frontend project can help manage data and give your project an edge as you can implement functionalities such as authentication with ease.

Top comments (0)