CRUD using Firebase In React
Simran Birla
Posted on June 7, 2021
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:
- Created a firebase account and create a web project in it.
- Install firebase tools:
npm install -g firebase-tools
npm install firebase
- 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-************",
});
- In your React app create a file firebase.js in src directory
- 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 };
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));
For sign out:
auth.signOut()
.then((res) => {
console.log(res);
})
.catch((err) => alert(err));
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
- Go to storage
- Create a new folder
const upload = storage.ref(`/<name of folder>/<name of file>`).put(<file>);
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)
});
}
);
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",
});
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"
});
Update:
When you want to change a field without overwriting the entire structure you use update()
db.collection("feed")
.doc(id)
.update({
name: "hello",
});
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!");
}
});
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(),
}))
);
}
);
Delete:
db.collection(`feeds`)
.doc(id)
.delete()
.then(() => {
alert("Deleted!!");
})
.catch((err) => alert(err));
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.
Posted on June 7, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.