Fetch and Send with Firestore using ReactJS
To perform fetch and send with Firestore using React require sending and receving data on the firestore database. Firestore is a NoSQL database developed by Google as an alternative to the Firebase database. It has been designed to provide a better developer experience and simplify the development process.
Prerequisites:
Approach
To perform fetch and send with Firestore using React first set up the firebase project configuration in the react application. create a database in the firestore and link a form to send data. Fetch this data form firestore using the collection method and display on the web page
Step to Create React Application and Installing Firebase
Step 1: Create a new React application. We use create-react-app to create our application.
npx create-react-app gfgfirestore
Step 2: Move to the project directory
cd gfgfirestore
Project Structure:
The project structure will look like this.
Step 3: After creating the ReactJS application, Install the firebase module using the following command:
npm i --save firebase@8.3.1
Dependencies list after installing packages
{
"dependencies": {
"@testing-library/jest-dom": "^5.17.0",
"@testing-library/react": "^13.4.0",
"@testing-library/user-event": "^13.5.0",
"firebase": "^8.3.1",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-scripts": "5.0.1",
"web-vitals": "^2.1.4"
}
}
Step 4: Go to your firebase dashboard and create a new project and copy your credentials.
const firebaseConfig = {
apiKey: "your api key",
authDomain: "your credentials",
projectId: "your credentials",
storageBucket: "your credentials",
messagingSenderId: "your credentials",
appId: "your credentials"
};
Example: Create a basic User Interface for adding data to the store and to read and display the data fetch from the firestore databse.
// Filename - App.js
import React from "react";
import "./App.css";
import Read from "./Read.js";
import Firestore from "./firestore";
function App() {
return (
<div
style={{ textAlign: "center", margin: "auto" }}
>
<h1 style={{ color: "green" }}>
GeeksforGeeks
</h1>
<h3>Form linked to firestore to send data</h3>
<Firestore />
<h3>Data fetch from firestore</h3>
<Read />
</div>
);
}
export default App;
// Filename - firebse.js
import firebase from "firebase";
const firebaseConfig = {
// Add your firebase credentials
apiKey: "your api key",
authDomain: "your credentials",
projectId: "your credentials",
storageBucket: "your credentials",
messagingSenderId: "your credentials",
appId: "your credentials",
};
// Initialize Firebase
firebase.initializeApp(firebaseConfig);
let db = firebase.firestore();
export default db;
import db from './firebase';
import { useState } from 'react';
const Firestore = () => {
const [name, Setname] = useState("");
const [age, Setage] = useState("");
const [course, Setcourse] = useState("");
const sub = (e) => {
e.preventDefault();
// Add data to the store
db.collection("data").add({
Nane: name,
Age: age,
CourseEnrolled: course
})
.then((docRef) => {
alert("Data Successfully Submitted");
})
.catch((error) => {
console.error("Error adding document: ", error);
});
}
return (
<div>
<center>
<form style={{ marginTop: "200px" }}
onSubmit={(event) => { sub(event) }}>
<input type="text" placeholder="your name"
onChange={(e) => { Setname(e.target.value) }} />
<br /><br />
<input type="number" placeholder="your age"
onChange={(e) => { Setage(e.target.value) }} />
<br /><br />
<input type="text" placeholder="Course Enrolled"
onChange={(e) => { Setcourse(e.target.value) }} />
<br /><br />
<button type="submit">Submit</button>
</form>
</center>
</div>
);
}
export default Firestore;
// Import Firestore database
import db from "./firebase";
import { useState } from "react";
// import "./read.css";
const Read = () => {
const [info, setInfo] = useState([]);
// Start the fetch operation as soon as
// the page loads
window.addEventListener("load", () => {
Fetchdata();
});
// Fetch the required data using the get() method
const Fetchdata = () => {
db.collection("data")
.get()
.then((querySnapshot) => {
// Loop through the data and store
// it in array to display
querySnapshot.forEach((element) => {
var data = element.data();
setInfo((arr) => [...arr, data]);
});
});
};
// Display the result on the page
return (
<div>
<center>
<h2>Student Details</h2>
</center>
{info.map((data) => (
<Frame
course={data.CourseEnrolled}
name={data.Nane}
age={data.Age}
/>
))}
</div>
);
};
// Define how each display entry will be structured
const Frame = ({ course, name, age }) => {
console.log(course + " " + name + " " + age);
return (
<center>
<div className="div">
<p>NAME : {name}</p>
<p>Age : {age}</p>
<p>Course : {course}</p>
</div>
</center>
);
};
export default Read;
Step to run the application: Use this command in the terminal in project directory.
npm start
Output: This output screens will be visible on the browser.
- Submitting the form after filling in the details to add the data
- The view of the data that is added to the store in firebase
- Records that are present in the database are displayed in our application.