0

Does anyone know the best way to make sure only data from the latest request to an api is being set as state in react? I'm getting race conditions in instant search where the old search term's results are being set after the new search term's results have been returned and set, some idiosyncrasies in the api's response time I guess

So say,

setInterval(async () => {
  const id = Math.random()
  setReqId(id)
  const resp = await axios.get('etc')
  if (reqId === id) {
    setResp(resp)
  }
}, 1)

But this doesn't work because reqId will not be updated by any subsequent calls to setReqId from other instances of the function

I tried useCallback like so but it didn't seem to work, I thought that was the whole point of useCallback that the callback gets updated with the new dependancies?

  const getReqId = useCallback(() => {
    return reqId
  }, [reqId])

Cheers!

I tried storing a current request Id but the variable value isn't updating within the function, so I also tried creating a getReqId using useCallback with a dependancy of reqId but that didn't get the latest value either

0 Answers0