๐ fix: infinite loop causing useEffect to fetch api continuously
Opened this issue ยท 0 comments
wmik commented
If you take these two out:
recallr/src/components/Records.js
Lines 112 to 113 in 3841c59
and remove them here too:
recallr/src/components/Records.js
Line 117 in 3841c59
and move this line
recallr/src/components/Records.js
Line 111 in 3841c59
inside this function
recallr/src/components/Records.js
Line 103 in 3841c59
it could solve the infinite loop that's causing that useEffect
to run continuously.
So it should look like this
useEffect(() => {
const fetchData = async () => {
await projectFirestore
.collection(currentUser.email)
.doc('records')
.collection('details')
.get()
.then((snapshot) => {
let records = snapshot.map((doc) => { // use .map() instead of .forEach() to minimize mutations
let currentId = doc.id;
let object = { ...doc.data(), id: currentId };
return object;
});
setRecords(records); // only runs if fetch runs successfully
})
.catch((err) => console.log(err));
};
fetchData();
}, [currentUser]);
or
useEffect(() => {
const fetchData = async () => {
await projectFirestore
.collection(currentUser.email)
.doc('records')
.collection('details')
.get()
.then((snapshot) => {
let records = snapshot.map((doc) => { // use .map() instead of forEach() to minimize mutations
let currentId = doc.id;
let object = { ...doc.data(), id: currentId };
return object;
});
setRecords(records); // only runs if the fetch runs successfully
})
.catch((err) => console.log(err));
};
if(records.length === 0) { // and add a condition
fetchData();
}
console.log(records);
console.log(count);
}, [currentUser, count, records]); // leave them in
Also fun fact if you use async/await you can access variables similar to regular code i.e
function transformSnapshot(doc) {
let currentId = doc.id;
let object = { ...doc.data(), id: currentId };
return object;
}
function request() {
let snapshot = await projectFirestore
.collection(currentUser.email)
.doc('records')
.collection('details')
.get(); // await until `.get()` is done executing
return snapshot.map(transformSnapshot);
}