Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

🐞 fix: infinite loop causing useEffect to fetch api continuously #1

Open
wmik opened this issue Nov 1, 2021 · 0 comments
Open

Comments

@wmik
Copy link

wmik commented Nov 1, 2021

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);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant