Next.js Discord

Discord Forum

why does my application keeps spam fetching data even though i only fetched it once ?

Unanswered
Raspberry Horntail posted this in #help-forum
Open in Discord
Raspberry HorntailOP
like i said in the title i don't know why does that keep hapenning this photo show multiple requests in a shor period of time (the token is for a fake acc btw)

16 Replies

Nile Crocodile
we can only guess without seeing any code
Raspberry HorntailOP
@Nile Crocodile
Nile Crocodile
if fetchUser is called inside of component, it will be executed every time component is rendered. It should be wrapped inside of useEffect hook with empty dependency array so it's called only once
and you should look into fetch function instead of XMLHttpRequest, it's outdated
Nile Crocodile
it should trigger at least once if it's used correctly... can you share more code? whole component if possible
Raspberry HorntailOP
@Nile Crocodile here is the whole code
Nile Crocodile
in a code block. if it's too long you can send only code relevant to the issue or use online editor like codesandbox and send link here
Raspberry HorntailOP
ok
Raspberry HorntailOP
oh i just noticed something the page doesn't get fully loaded i don't know why but i can see that there is some html elements not responding to events like clicking ... so that is the reason why useEffect isn't getting triggered @Nile Crocodile
Thanks for your help 🤍
@Raspberry Horntail Click to see attachment
Nile Crocodile
You cannot pass async functions to useEffect. If you want to fetch data inside of useEffect you'd do something like:
useEffect(() => {
   const fetchData = async () => {
      const resp = await fetch('...')
      const data = await resp.json()
      setData(data)
   }
   fetchData()
}, [])
However in your case, since you're using .then(), I think you could just do
useEffect(() => {
   fetchUser().then(user => setUser(user))
}, [])