DreMukare/recallr

๐Ÿž fix: infinite loop causing useEffect to fetch api continuously

Opened this issue ยท 0 comments

wmik commented

If you take these two out:

console.log(records);
console.log(count);

and remove them here too:

}, [currentUser, count, records]);

and move this line

setRecords(recs);

inside this function

.then((snapshot) => {

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);
}