0

Every time the request finishes loading I need to wait 10 seconds and fetch the data. So far I use 2 useEffects one to verify if the data is ready and the other to loop the counter until it gets to 0. I was wondering if there is a better way.

  useEffect(() => {
    if (!loading) {
      timer = setInterval(() => setCounter(value => value - 1), 1000)
    }
  }, [loading])

  useEffect(() => {
    if (counter === 0) {
      clearInterval(timer)
      refetch()
      setCounter(10)
    }
  }, [counter, refetch])
Julia
  • 1
  • 1
  • 1
    Why use an extra counter at all? Just `setInterval(refetch, 10 * 1000)`. – Bergi Jul 06 '22 at 14:26
  • 1
    Optimized for what? Memory usage? CPU cycles? – Heretic Monkey Jul 06 '22 at 14:34
  • one better way might be instead of polling: sockets. via - socket.io if the server is local. if it's not local and you're calling an external API then you are probably stuck with polling. – altruios Jul 06 '22 at 14:35
  • Does this answer your question? [Polling API every x seconds with react](https://stackoverflow.com/questions/46140764/polling-api-every-x-seconds-with-react) – Heretic Monkey Jul 06 '22 at 14:36

1 Answers1

0

Not a direct answer to your question, but you might be intersted in SWR. It provides React hooks for data fetching, and has options for polling at intervals, as well as other things (revalidate on focus, or manual revalidation for example).

B. Mélicque
  • 146
  • 5