DEV Community

Cover image for Firestore CRUD 101: Building Apps with React
Debajit Mallick
Debajit Mallick

Posted on

Firestore CRUD 101: Building Apps with React

Introduction

As a frontend developer, one of the challenges we face is setting up a backend, especially when we don't want to build a full-fledged backend from scratch. Firebase is a great solution for choosing a BAAS (Backend As A Service). Firebase Firestore Database is a flexible, scalable NoSQL cloud database that allows developers to store and sync data efficiently. It is a great choice for building applications that require real-time updates and complex queries. In this blog, we will learn how to create a basic CRUD (Create, Read, Update, Delete) application using Firebase Firestore 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

  1. Go to the Firebase Console.
  2. Create a new project.
  3. Navigate to Build > Firestore Database and click Create Database.
  4. Select the location and set the database rules to allow read and write for now:
   {
     "rules": {
       "users": {
         ".read": "true",
         ".write": "true"
       }
     }
   }
Enter fullscreen mode Exit fullscreen mode
  1. In Project Settings > General, find your Firebase SDK configuration. Note down the API keys and Firestore database settings.

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-firestore-crud
framework: react
language: JavaScript
...
cd firebase-firestore-crud
npm install firebase
Enter fullscreen mode Exit fullscreen mode

Step 3: Configuring Firebase in React

Inside your React project, create a firebase.js file:

import { initializeApp } from "firebase/app";
import { getFirestore } from "firebase/firestore";

const firebaseConfig = {
  apiKey: "YOUR_API_KEY",
  authDomain: "YOUR_AUTH_DOMAIN",
  projectId: "YOUR_PROJECT_ID",
  storageBucket: "YOUR_STORAGE_BUCKET",
  messagingSenderId: "YOUR_MESSAGING_SENDER_ID",
  appId: "YOUR_APP_ID"
};

const firebaseApp = initializeApp(firebaseConfig);
const db = getFirestore(firebaseApp);

export default db;
Enter fullscreen mode Exit fullscreen mode

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 { collection, addDoc, updateDoc, deleteDoc, doc, getDocs } from "firebase/firestore";
import db from "../firebase";

const Users = () => {
  const [data, setData] = useState([]);
  const [name, setName] = useState("");

  useEffect(() => {
    fetchUsers();
  }, []);

  const fetchUsers = async () => {
    const querySnapshot = await getDocs(collection(db, "users"));
    setData(querySnapshot.docs.map(doc => ({ id: doc.id, ...doc.data() })));
  };

  const handleCreate = async () => {
    await addDoc(collection(db, "users"), { name });
    setName("");
    fetchUsers();
  };

  const handleUpdate = async (id) => {
    const userRef = doc(db, "users", id);
    await updateDoc(userRef, { name });
    fetchUsers();
  };

  const handleDelete = async (id) => {
    await deleteDoc(doc(db, "users", id));
    fetchUsers();
  };

  return (
    <div>
      <h2>Users</h2>
      <input
        type="text"
        value={name}
        onChange={(e) => setName(e.target.value)}
        placeholder="Enter name"
      />
      <button onClick={handleCreate}>Add</button>

      <ul>
        {data.map((user) => (
          <li key={user.id}>
            {user.name}
            <button onClick={() => handleUpdate(user.id)}>Update</button>
            <button onClick={() => handleDelete(user.id)}>Delete</button>
          </li>
        ))}
      </ul>
    </div>
  );
};

export default Users;
Enter fullscreen mode Exit fullscreen mode

Step 5: Rendering the Component

In App.js, import and use Users:

import React from "react";
import Users from "./components/Users";

function App() {
  return (
    <div className="App">
      <Users />
    </div>
  );
}

export default App;
Enter fullscreen mode Exit fullscreen mode

Step 6: Running the App

Start your React app using:

npm run dev
Enter fullscreen mode Exit fullscreen mode

Conclusion

You have now created a simple CRUD app using Firebase Firestore and React! You can enhance this app by adding authentication, advanced validation, and more features like filtering or searching users. Firestore's structured data model allows more flexibility and scalability than Firebase Realtime Database, making it a great choice for production-ready applications. 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)