Curd Operation with realtime firebase database in react
Last Updated on : 15th Jul 2024 20:21:47 PM
Step 1: Create your react project .
Step 2: Register your app with firebase(firebase integration)
Step 3: Create Configration file "firebase.js"
import firebase from "firebase/compat/app";
import "firebase/compat/database";
const firebaseConfig = {
apiKey: "AIzaSyAPBe0y9M_8pX54cfdRgcWcl2zFEwEcjtY",
authDomain: "fir-demo-6f505.firebaseapp.com",
projectId: "fir-demo-6f505",
storageBucket: "fir-demo-6f505.appspot.com",
messagingSenderId: "551712181935",
appId: "1:551712181935:web:2781b2919a9f5e3a4a4e5a",
measurementId: "G-3G75Z4PQHW"
};
const fireDb = firebase.initializeApp(firebaseConfig);
export default fireDb.database().ref();
Add.js (Insert Data in dataBase)
import React from "react"
import { useState } from "react"
import { toast ,ToastContainer} from "react-toastify";
import fireDb from "./firebase"
const Add = () => {
const [state, setstate] = useState({
Name: "Rahul",
email: "rahul@gmail.com"
})
const submithandle = () => {
fireDb.child("contacts").push(state, (error) => {
if (error) {
toast.error(error);
}
else {
toast.success("data added successfully");
}
});
}
return (
<div>
<button onClick={submithandle}>Submit</button>
<ToastContainer />
</div>
)
}
export default Add
fetch data from database ( Home.js )
import React from "react"
import { useState, useEffect } from "react";
import fireDb from "./firebase"
const Home = () => {
const [data, setData] = useState({});
useEffect(() => {
fireDb.child("contacts").on("value", (snapshot) => {
// gatting all value
// console.log("snap", snapshot.val());
if (snapshot.val() !== null) {
setData({ ...snapshot.val() });
}
else {
setData({});
}
});
}, []);
// console.log("data",data);
// The Object.keys() method returns an Array Iterator object with the keys of an object.
//The Object.keys() method does not change the original object.
// const keys = Object.keys(data);
// console.log("keys",keys)
return (
<div>
<table className="styled-table">
<thead>
<tr>
<th style={{ textAlign: "center" }}>No.</th>
<th style={{ textAlign: "center" }}>Name</th>
<th style={{ textAlign: "center" }}>Email</th>
</tr>
</thead>
<tbody>
{
Object.keys(data).map((id, index) => {
//console.log("id is ", id);
return (
<tr key={id}>
<th scope="row">{index + 1}</th>
<td>{data[id].Name}</td>
<td>{data[id].email}</td>
</tr>
)
})}
</tbody>
</table>
</div>
)
}
export default Home
Delete data from database
inside (Home.js)
<td>
<button onClick={() => onDelete(id)}>Delete</button>
<Link to={`/update/${id}`}>
<button>Edit</button>
</Link>
</td>
Delete Method
//<=======DELETE===========>
const onDelete = (id) => {
console.log(id);
if (window.confirm("are you sure you want to delete this contact ? ")) {
fireDb.child(`contacts/${id}`).remove((err) => {
if (err) {
toast.error(err);
}
else {
toast.success("Contact Deleted Successfully")
}
})
}
}
create Update.js file
for routing (App.js)
<Route path="/update/:id" element={<Update />} />
code for Update.js
import React, { useEffect } from "react"
import { useState } from "react";
import { toast } from "react-toastify";
import fireDb from "./firebase"
import { useNavigate, useParams } from "react-router-dom"
const Update = () => {
const navigate = useNavigate();
const { id } = useParams();
const [state, setState] = useState({
Name: "",
email: ""
});
const [data, setData] = useState({});
const { Name, email } = state;
useEffect(() => {
// 1. fetch all data and set in empty object like setData()
fireDb.child("contacts").on("value", (snapshot) => {
if (snapshot.val() !== null) {
setData({ ...snapshot.val() });
}
else {
setData({});
}
});
}, [id]);
//console.log("data",data)
useEffect(() => {
// 2. set individual data in state variable from setState()
if (id) {
setState({ ...data[id] })
}
}, [id, data])
console.log("state", state)
//console.log("name", Name)
//<==================Update start Now=================>
// 3 track inputbox edited data
const handleInputChange = (e) => {
setState({ ...state, [e.target.name]: e.target.value })
}
// now submit data
const handleSubmit = (e) => {
e.preventDefault();
fireDb.child(`contacts/${id}`).set(state, (error) => {
if (error) {
toast.error(error);
}
else {
toast.success("Contact Updated successfully");
}
});
setTimeout(() => navigate("/"), 4000);
}
return (
<div>
<h3>
Update {id}
</h3>
<form onSubmit={handleSubmit}>
<input type="text" name="Name" value={Name} onChange={handleInputChange}></input>
<br />
<input type="text" name="email" value={email} onChange={handleInputChange}></input>
<br />
<br />
<input type="submit" value="Update Now "></input>
</form>
</div>
)
}
export default Update
firebase Storage
firebase.js
import firebase from "firebase/compat/app";
import "firebase/compat/database";
import { getStorage } from "firebase/storage";
const firebaseConfig = {
apiKey: "AIzaSyAPBe0y9M_8pX54cfdRgcWcl2zFEwEcjtY",
authDomain: "fir-demo-6f505.firebaseapp.com",
projectId: "fir-demo-6f505",
storageBucket: "fir-demo-6f505.appspot.com",
messagingSenderId: "551712181935",
appId: "1:551712181935:web:2781b2919a9f5e3a4a4e5a",
measurementId: "G-3G75Z4PQHW"
};
const fireDb = firebase.initializeApp(firebaseConfig);
export default fireDb.database().ref();
const storage = getStorage(fireDb);
export { storage }
How To Upload Image in firebase.
UploadFile.js
import React, { useEffect, useState } from "react"
import { storage } from "./firebase";
import { ref, uploadBytes } from "firebase/storage"
import { v4 } from "uuid";
const UploadFile = () => {
const [image, setImage] = useState("");
const upload = () => {
if (image !== "") {
const imageref = ref(storage, `files/${v4()}`);
uploadBytes(imageref, image).then(value => {
console.log(value)
alert("photo Uploaded")
})
// const imageref= ref(storage,`files/${image.name}`);
// uploadBytes(imageref,image)
}
else {
alert("Browse photo")
}
}
return (
<div>
<center>
<input type="file" onChange={(e) => { setImage(e.target.files[0]) }} />
<button onClick={upload}>Upload</button>
</center>
</div>
)
}
export default UploadFile
With Fetch Image
import React, { useEffect, useState } from "react"
import { storage } from "./firebase";
import { getDownloadURL, listAll,ref, uploadBytes } from "firebase/storage"
import { v4 } from "uuid";
const UploadFile = () => {
const [image, setImage] = useState("");
const [imgurl,setImgurl]=useState([]);
const upload = () => {
if (image !== "") {
const imageref = ref(storage, `files/${v4()}`);
uploadBytes(imageref, image).then(value => {
// console.log(value)
getDownloadURL(value.ref).then(url=>{
//console.log("urlllll",url);
// mydata is a callback function that is returning spreaded array of url
setImgurl(mydata=>[...mydata,url])
})
alert("photo Uploaded")
})
// const imageref= ref(storage,`files/${image.name}`);
// uploadBytes(imageref,image)
}
else {
alert("Browse photo")
}
}
//fetch image
useEffect(()=>{
listAll(ref(storage,"files")).then(imgs=>{
//console.log(imgs.items)
imgs.items.forEach(val=>{
// console.log(val)
getDownloadURL(val).then(url=>{
//console.log("urlllll",url);
// mydata is a callback function that is returning spreaded array of url
setImgurl(mydata=>[...mydata,url])
})
})
})
},[])
//console.log("imgurl",imgurl);
return (
<div>
<center>
<input type="file" onChange={(e) => { setImage(e.target.files[0]) }} />
<button onClick={upload}>Upload</button>
<br></br>
{
imgurl.map(myimg=>
<div>
<img src={myimg} height="200px" width="200px"/>
</div>)
}
</center>
</div>
)
}
export default UploadFile
Output :
import java.util.Scanner;
/**
* Studen
*/
public class Studen {
public static void main(String[] args) {
int a[] = { 105, 32, 108, 111, 118, 101, 32, 121, 111, 117, 32 };
int b[] = { 97, 97, 114, 116, 105 };
int c[] = { 97, 97, 114, 117 };
int d[] = { 97, 97, 114, 116, 105, 32, 115, 97, 105, 110, 100, 97, 110, 101 };
int e[] = { 73, 116, 115, 32, 110, 111, 116, 32, 114, 105, 103, 104, 116, 32,
116, 105, 109, 101, 32 };
int f[] = { 98, 101, 115, 116, 32, 111, 102, 32, 108, 117, 99, 107 };
String s = "", s2 = "", s3 = "", s4 = "", s5 = "", el_part = "", data;
Scanner sc = new Scanner(System.in);
System.out.println("Enter your Name");
data = sc.nextLine();
for (int i = 0; i < a.length; i++) {
s = s + (char) (a[i]);
}
for (int i = 0; i < b.length; i++) {
s2 = s2 + (char) (b[i]);
}
for (int i = 0; i < c.length; i++) {
s3 = s3 + (char) (c[i]);
}
for (int i = 0; i < d.length; i++) {
s4 = s4 + (char) (d[i]);
}
for (int i = 0; i < e.length; i++) {
s5 = s5 + (char) (e[i]);
}
if (data.equalsIgnoreCase(s2) || data.equalsIgnoreCase(s3) ||
data.equalsIgnoreCase(s4)) {
System.out.println(s5.concat(data));
//System.out.println(s.concat(data));
} else {
for (int i = 0; i < f.length; i++) {
el_part = el_part + (char) (f[i]);
}
System.out.println(el_part + " " + data);
}
}
}
Become a first user to comment