@seanred360
Posted
You have an infinite loop in your Advice.js. Currently you did not add a dependency array to your useEffect hook. This will cause the Advice component to repeatedly fetch the data many times per second.
what you have: useEffect(() => { (async () => await fetchItems())() })
when you add a dependency array: useEffect(() => { (async () => await fetchItems())() },[]) <------the [] here
a quick fix for this is to simply add your fetchItems function into useEffect and add an empty dependency array like this so that It runs once. Like this
useEffect(() => { const fetchItems = async () => { try { const response = await fetch(Api_url); const randomSlip = await response.json(); updateAdvice(randomSlip.slip.advice); updateID(randomSlip.slip.id); } catch (err) { console.log(err.stack); } }; (async () => await fetchItems())(); }, []);
When you add a dependency array you are telling useEffect to only run when the variable you put in there changes. Otherwise it will just run a million times a second repeatedly. If you have an empty array, you are telling useEffect to only run one time when the component renders. Unfortunately in React 18 this no longer works this way. An empty dependency array will run twice, which means you are fetching and rerendering twice. React does not want people to fetch data in their useEffect hooks anymore. We should move to using Suspense. I will make a pull request on your Github and show you what this looks like.
Marked as helpful
@Thedeezat
Posted
@seanred360 Thanks a lot for the explanation, i will check my Github now.