In the following code for example, how can I update react-query to wait for the previous call to be complete before starting the next one?
I’m trying to hit an API that has rate limiting to one call at a time but I have a list of calls I need to make, I get a 429 if more than one are done at the same time.
const [selection, setSelection] = React.useState([])
const results = useQueries(
selection.map(item => ({
queryKey: ['something', item]
queryFn: () => fetchItem(item)
})
)
const data = results.map(result => result.data)
2
Answers
I’m not aware of a built-in solution.
But how about this. A state that counts queries that have been run, and enables the next query.
You might need
staleTime: Infinity
to make sure the library doesn’t refetch all queries at the same time.Exactly as Anton suggested, React Query exposes a method called
enabled
. to illustrate it for you, use normal methods to loop through your items, and then only call RQ when the previous query finished, and then toggling theenabled
state. This is a very rough, more verbose example, and running replit here.I also included how to reuse the cache in the replit, so let me know if it makes sense. It can most definitely be optimised better, and the
setTimeout
is only to show you visually the progress.In the example from Anton, he uses the built in
useQueries
which would be a better approach. Hopefully between the two answers you can understand how to use RQ, how it works, and cool things you can do with it.