Building an app that allows users to add, fetch, and delete notes typically requires both backend and frontend technologies. However, thanks to Firebase, we can simplify this process significantly. While Firebase does not replace traditional backend technologies and has its own pros and cons, it offers a streamlined solution for this project.
In this blog, we will create a React app that enables users to add, fetch, and delete notes in real-time. This means any changes to the notes will be immediately reflected on all devices where the app is open in the browser.
Try it out from here: Click here
Prerequisites
To build this app, you should have some basic knowledge of frontend technologies such as HTML, CSS, and JavaScript. We will be using React.js to create this app, where the application will be divided into multiple components.
To handle the real-time fetching of notes, we will use the useEffect and useState hooks. If you are not familiar with these hooks, don’t worry — I will explain everything step by step. Without further ado, let’s build this application.
Creating a Firebase Project
First, visit the official Firebase website and log in or sign up using your Google account. Once logged in, click on the console button. In the Firebase console, you will see an option to create a new Firebase project. Click on this button to start creating your project.
Follow these steps to create a Firebase project. First, define the Firebase project name, and then click the continue button.
Next, disable Google Analytics for this project, then click the Create Project button.
After clicking the Create Project button, it will take some time to set up your Firebase project.
Creating a React Project
Creating a React project is straightforward. I use Vite for this purpose. To start, navigate to your desired folder and run the following command:
npm create vite@latest
You will be prompted to select your desired technologies, such as React and JavaScript. After making your selections, move to the project directory by using:
cd <folder-name>
Next, install the necessary dependencies by running:
npm install
Finally, start the development server with:
npm run dev
Congratulations, you have successfully created a React project!
Creating a Real-Time Database in Firebase
To create a real-time database in your Firebase project, follow these steps:
1.Visit the Firebase console and navigate to the Build section inside the Product Categories.
2. Click on Real-Time Database, click on the Create Database button and select the database location nearest to you.
3. Define the security rules to “Start in Test mode” for reading and writing to the real-time database. We will modify these security rules later to allow anyone to read and write data without authentication. However, keep in mind that this is not ideal for production environments due to security concerns.
Creating a Web Project in Firebase
Firebase is compatible with multiple platforms such as iOS, Android, Web, Unity, and Flutter. Since we are going to use the real-time database in our web app, we need to create a web project.
Click on the gear icon in the top left corner and select Project Settings. Then, scroll down the page and click on the Web icon.
Now, give your app a nickname and click on the Register App button.
Now, there are two ways to add the Firebase SDK to our web project:
- Using a <script> tag: This method can be used in JavaScript projects to utilize Firebase tools such as the real-time database.
- Via npm: This method is used to integrate Firebase into web apps using frameworks like React or Angular. Since we are building this app with React, we will use this method.
Installing Firebase in a React Project via NPM
To work with Firebase in our React project, we need to install the Firebase dependency via npm. Use the following command:
npm install firebase
After installing the Firebase dependency in our React app, we will have access to various methods and configuration details provided by Firebase.
Copying the Configuration Code into the React Project
To establish a connection between Firebase and our React app, we need some configuration details that allow the app to communicate with Firebase tools. Copy the configuration code provided by Firebase and paste it into your React app.
Initializing Firebase
To initialize Firebase in our React project, we will create a new JavaScript file named “firebaseConfig.js”. Inside this file, we will paste the Firebase configuration and initialize Firebase with this configuration using the “initializeApp” method provided by Firebase.
The initializeApp method in Firebase initializes a Firebase application instance by configuring it with a provided Firebase project’s settings, enabling access to Firebase services within a web application.
Initializing the Real-Time Database
After initializing the Firebase project, we need to set up the real-time database. To do this, we import the “getDatabase()” method from Firebase and initialize it with our Firebase app instance (app).
export const database = getDatabase(app);
By using getDatabase(), we ensure that our React application is connected to the Firebase Realtime Database and can perform real-time data operations effectively within our application.
Creating a Reference to the Database
After obtaining the Firebase Realtime Database instance, we need to create a reference to it using the “ref()” method imported from Firebase. This method takes two arguments: the first is the database instance itself (database), and the second is the key or path to the specific item or node in the database.
import { getDatabase, ref } from “firebase/database”;
// Create reference to the database
export const dbRef = ref(database, “item”);
In the above example, dbRef now represents a reference to the “item” node in our Firebase Realtime Database. This reference allows you to perform operations such as reading or writing data to and from this specific location within our React application.
Additionally, notice the use of the export keyword before database and dbRef variables. This allows us to use these variables in other components where we implement the application’s logic.
Setting Real-Time Database Security Rules
In the above section, we set Firebase to “Test mode”, a temporary state provided for testing purposes. Firebase will notify you via email after 30 days if you haven’t implemented proper security rules or authentication. During this period, anyone can access and modify your database, posing potential security risks if left unsecured.
Therefore, it’s crucial to review and update our Firebase database security rules appropriately so that at least we can read and write data in the database without authentication.
We need to change the below security rules from:
{
“rules”: {
“.read”: “now < 1720895400000”, // 2024-7-14
“.write”: “now < 1720895400000”, // 2024-7-14
}
}
to:
{
“rules”: {
“.read”: true,
“.write”: true,
}
}
By changing the Firebase real-time database rules from restricting access based on a specific timestamp (“now < 1720895400000”) to allowing unrestricted access (“.read”: true, “.write”: true), we effectively remove any restrictions on who can read from or write to the database.
To change these security rules, refer to the below image:
Pushing Data to the Firebase Database
We want to push data from our React app to Firebase’s database. To achieve this, we’ll gather the data locally from the user and then send it to the database when the user clicks a button.
- Rendering the Component:
<div className=“app_container”>
<h1>Firebase Notes App</h1>
<input
placeholder=“Enter item…”
value={item}
type=“text”
onChange={changeHandler}
/>
<button type=“button” onClick={clickHandler}>
Add item
</button>
<ul>
//Notes goes here
</ul>
</div>
The component renders an input field and a button. The input field is controlled by the item state variable and updates whenever the user types via the changeHandler function. When the user clicks the button, the clickHandler function is triggered, which pushes the input data to Firebase.
- State Management:
const [item, setItem] = useState(“”);
The item is a state variable that holds the current input value and it updates via the setItem function.
- Handling Input Changes:
function changeHandler(e) {
// Update the state with the value from the input field
setItem(e.target.value);
}
The changeHandler function updates the item state variable with the current value of the input field whenever the user types.
- Adding Items to Firebase:
function clickHandler() {
// Check if the input field is empty
if (!item) {
alert(“Please enter a item”);
return;
}
// Push data to the database
push(dbRef, item);
// Clear the input field
setItem(“”);
}
The clickHandler function checks if the input field is empty. If not, it pushes the new item to Firebase using push(dbRef, item) and then clears the input field by setting item to an empty string.
push(dbRef, item)
The push method is a Firebase Realtime Database function that allows you to add new data to a specified location in your database. It generates a unique key for each new child node, ensuring that your data entries do not overwrite each other.
The push method is called with two arguments:
- dbRef: The database reference where the new data should be added.
- item: The data you want to add to the database.
By using the above setup, we effectively gather data from the user through the input field and push it to the Firebase Realtime Database when the user clicks the “Add item” button, enabling the app’s functionality for adding notes.
Fetching Data from the Firebase Database
To fetch data from the Firebase Realtime Database, we use the onValue method, which listens for changes to the data at a specified database reference and retrieves the current data as a snapshot.
- State Management:
const [list, setList] = useState();
The list state variable holds the data fetched from the database, and setList is used to update this state.
- Fetching Data Using useEffect:
useEffect(() => {
// Get data from the database
onValue(dbRef, function (snapshot) {
const data = snapshot.val();
if (data) {
const valueWithKey = Object.entries(data);
setList(valueWithKey);
} else setList([]);
});
}, []);
The useEffect hook is used to run the data fetching code when the component mounts. The empty dependency array [] ensures this effect runs only once.
- onValue Method:
The onValue method from Firebase is used to set up a real-time listener on the database reference dbRef.
This method takes two arguments: the database reference and a callback function that executes whenever the data at this reference changes.
- Data Snapshot:
Inside the callback function, snapshot.val() retrieves the current data at the database reference.
If data is not null, the code uses Object.entries(data) to convert the data object into an array of key-value pairs and stores it in valueWithKey. setList(valueWithKey) updates the list state variable with this array.
Rendering Data onto the UI
As the data is retrieved in the form of an array, we utilize the map method to iterate through each item and dynamically render it onto the screen. This approach ensures that each piece of data is efficiently displayed in the user interface, enabling seamless interaction with the Firebase data within our React application.
<ul>
{list?.length >= 1 ? (
list?.map((item) => {
return (
<li key={item[0]} onDoubleClick={() => deleteHandler(item[0])}>
{item[1]}
</li>
);
})
) : (
<p>Add list item…</p>
)}
</ul>
Deleting Data in the Database
To implement a feature where a user can delete a note by double-clicking on it, we need to set up an event that handles this action.
function deleteHandler(id) {
// Remove the item from the database
const exactItemInDB = ref(database, `item/${id}`);
remove(exactItemInDB);
}
The deleteHandler function is designed for this purpose. When a user double-clicks on a list item, this function is triggered.
The id parameter represents the unique identifier of the note item that the user wants to delete. It’s passed to the function when the user double-clicks on a specific list item.
const exactItemInDB = ref(database, `item/${id}`);
It creates a reference to the exact location of the note item in the Firebase database. The ref function from Firebase is used for this purpose. By specifying “item/${id}”, we construct a path that points directly to the item with the given id under the “item” node in the database.
remove(exactItemInDB);
Here, the remove function from Firebase’s API is called with “exactItemInDB” as an argument. This function call effectively deletes the item referenced by “exactItemInDB” from the Firebase Realtime Database. As a result, the note item is removed not only from the UI but also from the database itself.
Get the complete code from GitHub: Click here
Conclusion
In this blog, we’ve covered the essential steps to integrate Firebase’s Realtime Database into a React application. From setting up Firebase and managing state with React hooks, to pushing, fetching, and deleting data.
We’ve explored practical techniques for building interactive and efficient web applications. These skills not only enhance our ability to manage real-time data effectively but also provide a solid foundation for creating responsive and scalable solutions.
Also, if you are looking for a JavaScript or React job, please search for them on Talent500.co
Add comment