Building the simple CRUD application using ReactJS and Firebase
Building frontend is so fun, you can structure the design of a web app in the way you want, with a little bit of animation from left and right. The carousels scrolling and whatnot. But if we want to build something that has full functionality. What should we do? Well go and connect your code with Firebase.
I feel as a Frontend developer there are lots of options on the internet which gives us choice and varieties to use without investing money and a little bit of our mind. Firebase is one that Backend- as-a-service platform, that gives you the freedom to explore your frontend building ability while it takes care of many other features that generally a web application should have.
Here we will discuss a similar web application that is efficient and as a coder will teach how important it is to understand “how an interactive Web application works?”. We are building a simple CRUD application in ReactJS and Firebase.
Application Demo video.
What is CRUD?
CRUD stands for Create, Read Update, and Delete. If you will look into the deeper picture you will notice that is exactly what any interactive web application will do.
You create something on a web page for example take a SignUp page, enter details, and click on signup. A data is Created. Now according to the data, you will be redirected to a page, that is a Reading of the data you have entered. When you make some changes on the webpage it is Updated in the database and similarly, how Delete function deletes that particular record that you have clicked on.
List of Concepts You will learn.
- CRUD is the most important functionality that you as a new coder should know.
- Every interactive software, web app, and mobile app that you see around you is more or less doing CRUD.
- If this is your first application on Reactjs and Firebase this is the best way to understand how the frontend and database interact.
- State Management, Real-time data updates, Building forms, and data collection through it, error handling.
What exactly we will build?
- Assuming you are a new developer I am not going with some bigger example, so here we will ask users to enter their name and age on a form in the frontend.
- We will store the data entered by users into Firestore.
- We will display the list of names and their respective age on the front end.
- On the same data, we will make some changes and update the data.
- We will also delete some data by clicking on Delete button.
Code discussion.
You don’t need to have prerequisite knowledge of Firebase here but I hope you have some knowledge of ReactJS.
Either way, I will explain the code step by step.
1. Connect Firebase
- First, you have to register your app on Firebase.
- Please refer to the linked blog if you don’t know how to create a project on Firebase and connect it with ReactJS. (click here).
- Now after Connecting the Firebase and ReactJS application, we need to create Firestore database for our application.
2. Create Firestore
- Go on the left side tab in your project in Firebase and click on Build.

- Now Click on Firestore Database.

- This will assign a Firestore Database to our project but we still need to create a database so you will see a big button on your screen saying “Create database”. Click on the button.

- In the next image you will see Firebase also asks you what kind of Firestore you want, here you can go with Test mode cause we are just creating a simple project. But definitely try the production mode as well.
- In test mode your data had read/write for anyone for the next 30 days.
- In production mode your data will not be accessible to anyone from the start until and unless you authorize anyone.

- Firebase will ask you the region so that it will assign you the nearest location for your Firestore and your work will be more feasible, you can go with below selected option and click on Enable.

- Firebase will take a minute or some second and it will create an empty Firestore database for you.

- The below image is showing how database will look after we have stored some values.

3. Open VS Code or your favorite Code editor.
- Go to the terminal and type
npx create-react-app applicationname
- This will create a project by the name “applicationname“.
- Open this folder that you have just created.
- React will download lots of files, if you are a new developer remember you don’t need any of these files currently.
- Go to the src folder and create a file named crud.js (you can name it anything).
4. Discussing crud.js.
crud.js
import React, { useState, useEffect } from 'react';
import './App.css';
import { db } from './firebase';
import { collection, getDocs, addDoc, updateDoc, deleteDoc,doc} from 'firebase/firestore';
export default function Crud(){
const [newName, setNewName] = useState("");
const[newAge, setNewAge] = useState(0);
const [id, setId] = useState('');
const[users, setUsers] = useState([]);
const usersCollectionRef = collection(db, 'users');
const[show, setShow] = useState(false);
useEffect(() => {
const getUsers = async () => {
const data = await getDocs(usersCollectionRef)
//console.log(data);
setUsers(data.docs.map(doc => ({...doc.data(), id: doc.id})));
};
getUsers();
},[newName, newAge, users]);
const createUser = async (e) =>{
e.preventDefault();
await addDoc(usersCollectionRef, {name: newName, age: Number(newAge) });
setNewAge(0);
setNewName("");
};
const updateUser = async() =>{
const userDoc = doc (db, "users", id);
const newFields = { name: newName, age: Number(newAge) };
await updateDoc(userDoc, newFields);
setShow(false);
setNewName("");
setNewAge(0);
}
const deleteUser = async(id) =>{
const userDoc = doc (db, "users", id);
await deleteDoc(userDoc);
}
const editUser = async(id, name,age)=>{
setNewName(name);
setNewAge(age);
setId(id);
setShow(true);
}
return (
<div className="App">
<h3 className='headtitle'>Enter Name and Age for <span>CRUD</span> </h3>
<div className="App-header">
<input placeholder='Enter Name' value={newName}
onChange={(event) => {setNewName(event.target.value)}} />
<input placeholder='Enter Age' value={newAge} type='number'
onChange={(event) => {setNewAge(event.target.value)}} />
{!show? <button className='createbtn' onClick={createUser} >CREATE</button>:
<button className='updatebtn' onClick={updateUser} >UPDATE</button>
}
</div>
<div className="App-body">
{users.map((user) =>(
<div key={user.id}>
{""}
<div className="name_div">
<h3>Name: {user.name} </h3>
<h3>Age: {user.age} </h3>
</div>
<button className='editbtn' onClick={() => {editUser(user.id, user.name, user.age)}}> EDIT </button>
<button className='deletebtn' onClick={() => {deleteUser(user.id)}}>DELETE</button>
</div>
)
)}
</div>
</div>
);
}
The above code is the whole code that you need for this application. The other thing you will need will be some tweaks in app.js, which I will tell you later.
Code Explanation.
const [newName, setNewName] = useState("");
const[newAge, setNewAge] = useState(0);
const [id, setId] = useState('');
const[users, setUsers] = useState([]);
const usersCollectionRef = collection(db, 'users');
const[show, setShow] = useState(false);
Variables
const [newName, setNewName] will store the name entered by the user.
const[newAge, setNewAge] would store the age entered by the user.
const [id, setId] we will use to store the auto-generated id from Firestore.
This Id will help us in recognising the record and in return which will help us in deleting it.
const[users, setUsers] array has been defined which will be used for storing the data returned from the Firestore. (where data is stored).
<div className="App-header">
<input placeholder='Enter Name' value={newName}
onChange={(event) => {setNewName(event.target.value)}} />
<input placeholder='Enter Age' value={newAge} type='number'
onChange={(event) => {setNewAge(event.target.value)}} />
{!show? <button className='createbtn' onClick={createUser} >CREATE</button>:
<button className='updatebtn' onClick={updateUser} >UPDATE</button>
}
</div>
Let’s start with the frontend part of the code then we will go into detail with the function part.
<input placeholder='Enter Name' value={newName}
onChange={(event) => {setNewName(event.target.value)}} />
Here input tag will hold the name entered by the user and setNewName will store the value in the newName.
<input placeholder='Enter Age' value={newAge} type='number'
onChange={(event) => {setNewAge(event.target.value)}} />
This input will hold the age entered by the user and store this value into newAge.
{!show? <button className='createbtn' onClick={createUser} >CREATE</button>:
<button className='updatebtn' onClick={updateUser} >UPDATE</button>
Here we have created 2 buttons Create and Update button. The Create button will create the record entered by the user and the Update button will update the edited record by the user.
We have given the boolean value of false to show variable. Here we will check if the show is true then we will show the Create button but if it is false then we will show the update button.
We will change the value of the show variable in the edit function which you will see in the next section when we will be talking about the edit or update function.
Now if you notice onClick of the Create button is calling the function createUser and similarly for the update button we have the onClick function named updateUser. Keep in mind these functions and now we will directly go and see how this function works.
const createUser = async (e) =>{
e.preventDefault();
await addDoc(usersCollectionRef, {name: newName, age: Number(newAge) });
setNewAge(0);
setNewName("");
};
The createUser function creates a record and stores it in the Firestore. Before we talk about the addDoc function let’s talk about userCollectionRef.
const usersCollectionRef = collection(db, 'users');
The collection is a Firestore function that we have imported from Firebase (See the top of the code), this function we have used to make a reference to the database ‘db’, which we have created in the firebase.js file. ‘users’ is the name of the collection to which we want to refer, you can put any name instead of ‘users’. So basically this ‘users’ is like a table that will hold the record entered by the users.
In userCollectionRef, we are saving the reference to the database in this case collection.
Why?
Through this reference we will do the database operations like reading, writing, deleting, and updating.
await addDoc(usersCollectionRef, {name: newName, age: Number(newAge) });
To know deep about it you have to go and check the cloud Firestore data model.
addDoc function is imported from Firestore/firebase. This function is used to add data into Firestore. It takes 2 arguments, one is the reference(where you want to store data) and the other is the data you want to store.
setNewAge(0);
setNewName("");
setNewAge and setNewName here will make the Name and Age input box blank after storing the value in the Firestore.
Updating the Record
const updateUser = async() =>{
const userDoc = doc (db, "users", id);
const newFields = { name: newName, age: Number(newAge) };
await updateDoc(userDoc, newFields);
setShow(false);
setNewName("");
setNewAge(0);
}
updateUser is needed when the user wants to edit anything that is already stored in the Firestore.
const userDoc = doc (db, "users", id);
userDoc here will refer to the “users” collection with its id.
Reading Data from Firestore
useEffect(() => {
const getUsers = async () => {
const data = await getDocs(usersCollectionRef)
//console.log(data);
setUsers(data.docs.map(doc => ({...doc.data(), id: doc.id})));
};
getUsers();
},[newName, newAge, users]);
If you don’t know about use effect you can read it here in detail, but we are using it here so that it reads data from the database that we have created on Firestore. In layman’s terms here the main functionality of use effect is that it will render any function only once at the start of loading of the page unless it is not said so.
Inside the useEffect, a getUsers is an asynchronous function that fetches data from the usersCollectionRef, which is a firebase collection containing user data.
The retrieved data is mapped using data.docs.map(doc => ({…doc.data(), id: doc.id})) to convert it into an array of JavaScript objects. Each object contains the document data (user data) and the id of the document. This array of objects is then used to set the “users” state variable.
The useEffect is set to run when any of the specified dependencies (newName, newAge, users) change (this will help our code when the user updates the data). It means that whenever these dependencies change, the getUsers function will be called to fetch and update the user data in the component’s state.
We are finished here with all the functions that will help us in doing the CRUD application. Now we should talk about the code that will display these data.
How to display data.
Code
This section of div is where we are displaying the age and the age which is entered by the user. As the data entered is already stored in the firestore. We also have Edit and Delete buttons in this div.
We will go step by step with the code.
<div className="App-body">
{users.map((user) =>(
<div key={user.id}>
{""}
<div className="name_div">
<h3>Name: {user.name} </h3>
<h3>Age: {user.age} </h3>
</div>
<button className='editbtn' onClick={() => {editUser(user.id, user.name, user.age)}}> EDIT </button>
<button className='deletebtn' onClick={() => {deleteUser(user.id)}}>DELETE</button>
</div>
)
)}
</div>
users.map((user) => (
here map function will iterate over the users array and return a React component for each user.
<div key={user.id}>
This <div> is a parent div for each user. The key prop is set to the user.id which will efficiently update and render the list of users. We need to add a key while iterating the array of data.
<h3>Name: {user.name} </h3>
This line displays the user’s name. The user.name variable should contain the user’s name retrieved from the Firestore database.
<h3>Age: {user.age} </h3>
This line displays the user’s age. The user.age variable should contain the user’s age retrieved from the Firestore database.
<button className='editbtn' onClick={() => {editUser(user.id, user.name, user.age)}}> EDIT </button>
This is an “EDIT” button. When clicked, it invokes the editUser function with the user.id, user.name, and user.age as parameters. The editUser function will be used to edit the user’s information.
<button className='deletebtn' onClick={() => {deleteUser(user.id)}}>DELETE</button>
This is a “DELETE” button. When clicked, it invokes the deleteUser function with the user.id as a parameter. As clear from the name deleteUser function will be used to delete the user from the database.
Tweak in App.js
Now the last thing you have to do is import and add your crud.js in the App.js file. Then the real magic happens.
import Crud from './Crud';
import './App.css';
function App() {
return(
<>
<Crud />
</>
)
}
export default App;
And now you know how to make a CRUD application in ReactJS and Firebase.
You must be logged in to post a comment.