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;
CodePudding user response:
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))
}, [])
CodePudding user response:
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))
},[])