skip to Main Content

I’m reading data from firestore and displaying them in UI. It’s working at first, then I’m getting Failed to load resource: the server responded with a status of 429 () in the console. I figured react is triggering rerenders and querying data from firestore continuously. I’m using useState hook to assign data to a variable. Could someone explain why my code is doing that?

import { initializeApp } from "firebase/app";
import { getFirestore, collection, getDocs } from 'firebase/firestore/lite';
import { useState } from "react";

const firebaseConfig = {
  //firebase config
};
const app = initializeApp(firebaseConfig);

//Get firestore
const db = getFirestore(app);

//Function to read DB
async function getCollection(db, colName) {
  const dataCol = collection(db, colName);
  const dataSnapshot = await getDocs(dataCol);
  const DataList = dataSnapshot.docs.map(doc => doc.data());
  return DataList;
}

function App() {
  //Var to keep data
  const [data, setData] = useState([]);

  //Calling DB
  getCollection(db, 'SensorData')
    .then(obj => setData(obj))
    .catch(err => console.log(err))

  return (
    <div className="App">
      {/* Rendering Data */}
      {data.map((element) => 
                              <div>
                                <p>LDR : {element.LDR}</p>
                                <p>PIR : {element.PIR}</p>
                              </div>)
      }
    </div>
  );
}

export default App;

2

Answers


  1. Try put getCollection in useEffect with an empty dependency so it only run one on render

    useEffect(() => {
      getCollection(db, 'SensorData')
      .then(obj => setData(obj))
      .catch(err => console.log(err))
    }, [])
    
    Login or Signup to reply.
  2. If you want to fetch Data only once from your store, use useEffect instead of Calling db in the body of the FC

      useEffect(() => {
       getCollection(db, 'SensorData')
        .then(obj => setData(obj))
        .catch(err => console.log(err))
      },[])
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search