Using Firestore with React to Store and Retrieve Data

 we will create a simple React application that uses Firebase Firestore to store and retrieve a list of items.

Step 1: Create a React App

Use Create React App to create your project:

bash

Copy code
npx create-react-app firestore-example
cd firestore-example

Step 2: Install Firebase

Install Firebase SDK:

bash

Copy code
npm install firebase

Step 3: Configure Firebase

Create a firebaseConfig.js file in the src directory with your Firebase credentials:

javascript

Copy code
// src/firebaseConfig.js
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 app = initializeApp(firebaseConfig);
const db = getFirestore(app);

export { db };

Step 4: Create a Component to Manage Items

Create an Items.js component to add and display items:

javascript

Copy code
// src/Items.js
import React, { useState, useEffect } from 'react';
import { db } from './firebaseConfig';
import { collection, addDoc, getDocs } from 'firebase/firestore';

const Items = () => {
    const [items, setItems] = useState([]);
    const [newItem, setNewItem] = useState('');

    const itemsCollectionRef = collection(db, 'items');

    const fetchItems = async () => {
        const data = await getDocs(itemsCollectionRef);
        setItems(data.docs.map((doc) => ({ ...doc.data(), id: doc.id })));
    };

    const addItem = async () => {
        await addDoc(itemsCollectionRef, { name: newItem });
        setNewItem('');
        fetchItems(); // Refresh the item list
    };

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

    return (
        <div>
            <h2>Firestore Items</h2>
            <input
                type="text"
                value={newItem}
                onChange={(e) => setNewItem(e.target.value)}
                placeholder="Add a new item"
            />
            <button onClick={addItem}>Add Item</button>
            <ul>
                {items.map(item => (
                    <li key={item.id}>{item.name}</li>
                ))}
            </ul>
        </div>
    );
};

export default Items;

Step 5: Use the Items Component

Include the Items component in your App.js:

javascript

Copy code
// src/App.js
import React from 'react';
import Items from './Items';

const App = () => {
    return (
        <div className="App">
            <Items />
        </div>
    );
};

export default App;

Leave a comment

Your email address will not be published. Required fields are marked *