Introduction
As a frontend developer, all we suffer is to get a backend, as most of the time we don't want to build a full-fledged backend. Firebase is a great saviour for choosing a BAAS (Backend As A Service). Firebase Realtime Database is a cloud-hosted NoSQL database that allows developers to store and sync data in real time. It is a great choice for building applications that require instant updates. In this blog, we will learn how to create a basic CRUD (Create, Read, Update, Delete) application using Firebase Realtime Database and React.
Prerequisites
Before we start, ensure you have the following installed:
- Node.js (latest LTS version)
- npm or yarn
- A Firebase account with a project setup
Step 1: Setting Up Firebase
- Go to the Firebase Console.
- Create a new project.
- Navigate to Build > Realtime Database and click Create Database.
- Select the location and set the database rules to allow read and write for now:
{
"rules": {
".read": "true",
".write": "true"
}
}
- In Project Settings > General, find your Firebase SDK configuration. Note down the API keys and database URL.
Step 2: Creating a React App
Run the following command to create a new React project using Vite:
npm create vite@latest
Project name: firebase-crud
framework: react
language: JavaScript
...
cd firebase-crud
npm install firebase
Step 3: Configuring Firebase in React
Inside your React project, create a firebase.js
file:
import { initializeApp } from "firebase/app";
import { getDatabase } from "firebase/database";
const firebaseConfig = {
apiKey: "YOUR_API_KEY",
authDomain: "YOUR_AUTH_DOMAIN",
databaseURL: "YOUR_DATABASE_URL",
projectId: "YOUR_PROJECT_ID",
storageBucket: "YOUR_STORAGE_BUCKET",
messagingSenderId: "YOUR_MESSAGING_SENDER_ID",
appId: "YOUR_APP_ID"
};
const firebaseApp = initializeApp(firebaseConfig);
const database = getDatabase(firebaseApp);
export default database;
Step 4: Implementing CRUD Operations for users
Creating a Component
Inside src
, create a components
folder and add Users.js
:
import React, { useState, useEffect } from "react";
import { ref, set, update, remove, onValue } from "firebase/database";
import database from "../firebase";
const Users = () => {
const [data, setData] = useState({});
const [name, setName] = useState("");
useEffect(() => {
const usersRef = ref(database, "users");
onValue(usersRef, (snapshot) => {
setData(snapshot.val() || {});
});
}, []);
const handleCreate = () => {
const id = Date.now().toString();
set(ref(database, `users/${id}`), { name });
setName("");
};
const handleUpdate = (id) => {
update(ref(database, `users/${id}`), { name });
};
const handleDelete = (id) => {
remove(ref(database, `users/${id}`));
};
return (
<div>
<h2>CRUD with Firebase</h2>
<input
type="text"
value={name}
onChange={(e) => setName(e.target.value)}
placeholder="Enter name"
/>
<button onClick={handleCreate}>Add</button>
<ul>
{Object.keys(data).map((id) => (
<li key={id}>
{data[id].name}
<button onClick={() => handleUpdate(id)}>Update</button>
<button onClick={() => handleDelete(id)}>Delete</button>
</li>
))}
</ul>
</div>
);
};
export default Users;
Step 5: Rendering the Component
In App.js
, import and use CrudOperations
:
import React from "react";
import Users from "./components/Users";
function App() {
return (
<div className="App">
<Users />
</div>
);
}
export default App;
Step 6: Running the App
Start your React app using:
npm run dev
Conclusion
You have now created a simple CRUD app using Firebase Realtime Database and React! Now you can go to the next step by adding some more functionality where you add more fields for the user and create a user details page maybe. This example can be expanded with authentication, advanced validation, and real-time synchronization for a more robust application. If you like this blog and want to learn more about Frontend Development and Software Engineering you can follow me on Dev.to.
Top comments (0)