Crud operation using rect and firebase
In this article I am going to show CRUD(Create, Read, Update Delete) operation using React and firebase
In this example I am not going to show you firebase setup I am assume that you have a firebase project and want to work on it.
Copy your firebase configaration info from your frirebase project
Cretae a file called firebase-config under project root folder or what are you like I am going to create this file inside src folder and setup this file like bellow
firebase-config.js
import { initializeApp } from "firebase/app";
const firebaseConfig = {
apiKey: "",
authDomain: "",
projectId: "",
storageBucket: "",
messagingSenderId: "",
appId: "",
};
export const app = initializeApp(firebaseConfig);
Now, ready to start working our react project........
app.js
import React, { useState, useEffect } from "react";
import { getFirestore } from "firebase/firestore";
import { app } from "../src/firebase-config";
import {
collection,
getDocs,
addDoc,
doc,
deleteDoc,
updateDoc,
} from "firebase/firestore";
export default function App() {
const [products, setProduct] = useState({
productName: String,
price: Number,
});
const db = getFirestore(app);
//setup a firebase collection
const collectionRef = collection(db, "productColl");
//save data to firebase
const addProduct = async () => {
if (!products.productName || !products.price) {
alert("Product object is empty");
} else {
//Create new collection in firebase
await addDoc(collectionRef, { ...products });
//page reloading
window.location.reload();
}
};
useEffect(() => {
//get data from firebase
const getProduct = async () => {
//Read collections from firebase
const data = await getDocs(collectionRef);
setProduct(data.docs.map((doc) => ({ ...doc.data(), id: doc.id })));
};
getProduct();
}, []);
//update product
const updateProduct = async (id) => {
let productName, price;
//take user input
productName = prompt("Enter new name:");
price = prompt("Price:");
//Prepare a specifie collection to update using doc()
//doc(db, "collection name", collection id)
const productDoc = doc(db, "productColl", id);
//cretae a new object with new value
const newValue = {
productName: productName ? productName : products.productName,
price: price ? Number(price) : products.price,
};
if (window.confirm("Do you want to update?") === true) {
//Update a collection in firebase
await updateDoc(productDoc, { ...newValue });
//page reloading
window.location.reload();
}
};
//delete data from firebase
const dalateProduct = async (id) => {
//Prepare a specifie collection to dalete using doc()
//doc(db, "collection name", collection id)
const productDoc = doc(db, "productColl", id);
if (window.confirm("Do you want to delate?") === true) {
//Delete a collection from firebase
await deleteDoc(productDoc);
//page reloading
window.location.reload();
}
};
return (
<div>
<h1>CRUD Operation using firebase & React</h1>
<input
type="text"
onChange={(e) =>
setProduct({ ...products, productName: e.target.value })
}
placeholder="Product name"
></input>
<input
type="number"
onChange={(e) => setProduct({ ...products, price: e.target.value })}
placeholder="Product price"
></input>
<button type="button" onClick={() => addProduct()}>
Save
</button>
<h1>All product list</h1>
{products.length > 0
? products.map((product) => {
return (
<div key={product.id}>
<p>Name: {product.productName}</p>
<p>Price: {product.price}</p>
<button onClick={() => updateProduct(product.id)} type="button">
Update
</button>
<button onClick={() => dalateProduct(product.id)} type="button">
Delete
</button>
</div>
);
})
: null}
</div>
);
}