Fetch and Send with Firestore using ReactJS
Last Updated :
07 Jun, 2024
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 [email protected]
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.
JavaScript
// 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;
JavaScript
// 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;
JavaScript
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;
JavaScript
// 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.

Similar Reads
Create ToDo App using ReactJS
In this article, we will create a to-do app to understand the basics of ReactJS. We will be working with class based components in this application and use the React-Bootstrap module to style the components. This to-do list can add new tasks we can also delete the tasks by clicking on them. The logi
3 min read
Writing and Reading Data in Cloud Firestore
Cloud Firestore is a NoSQL document database built for automatic scaling, high performance, and ease of application development. In this article, we will explore how to write and read data in Cloud Firestore along with complete with detailed examples and. Whether you are a beginner or looking to ref
8 min read
How to authenticate with google using firebase in React ?
The following approach covers how to authenticate with Google using firebase in react. We have used firebase module to achieve so. Creating React Application And Installing Module: Step 1: Create a React myapp using the following command: npx create-react-app myappStep 2: After creating your project
3 min read
Create a weather Application using React Redux
Weather App is a web application designed to provide real-time weather information for any location worldwide. In this article, we will make a Weather App using React and Redux. It offers a seamless and intuitive user experience, allowing users to easily access accurate weather forecasts ( temperatu
4 min read
How to send email verification link with firebase using ReactJS?
Email verification is a crucial step in user authentication and account security. It ensures that users provide a valid email address and allows you to verify their identity before granting them access to certain features or functionalities. Firebase, a powerful platform for building web and mobile
3 min read
Google SignIn using Firebase Authentication in ReactJS
Firebase simplifies mobile and web app development by offering pre-built features like user authentication (email/password, Google Sign-In, etc.) without the need to build complex backends. This saves time and resources for developers.In this article, we will discuss about the Google Sign-In feature
4 min read
How to send one or more files to an API using axios in ReactJS?
Assuming that you want to send multiple files from the front-end, i.e., the React app, to the server using Axios. For that, there are two approaches as shown below: Send multiple requests while attaching a single file in each request.Send a single request while attaching multiple files in that reque
3 min read
How to get current date and time in firebase using ReactJS ?
This article provides a detailed walkthrough on obtaining the current date and time in a Firebase environment using ReactJS. Readers will gain insights into the implementation process, enabling date and time functionalities into their React projects powered by Firebase. Prerequisites:Node JS or NPMR
2 min read
How to Upload Image and Preview it Using ReactJS?
In React upload and preview images improve the user experience of the application, It's typical for online apps to provide image upload capability that enables users to choose and upload photographs. We simply upload a photo from our local device to our React Project and preview it using a static me
2 min read
How To Create A Multi-Page Website Using ReactJS?
Multi-page website using ReactJS is the core for building complex web applications that require multiple views or pages. Previously where each page reloads entirely, ReactJS allows you to navigate between different pages without reloading the whole page thanks to libraries like React Router. In this
4 min read