Home > OS >  How can I delay React Query fetch calls?
How can I delay React Query fetch calls?

Time:10-17

The API i am using (Jikan) just upgraded to v4 and now I can't make more than 2 calls at the same time without getting an error of too many requests. I am using react query(v3) with the useQuery hook. I have 4 calls on a page (getting top anime by popularity, upcoming, etc.). I have 2 of them working fine, the other I would like to delay so I can still use React Query. I am stuck on how I can do this. I believe it is due to a closure. I am currently using setTimeout to delay but I need the result of that. Here is what I have:

    const {data: animeUpcoming, isLoading: animeUpcomingLoading} = useQuery('animeByUpcoming', animeUpcomingFetcher)
    
    const animeUpcomingFetcher = () => {
      let res

      setTimeout(async () => {
          res = await axios('https://api.jikan.moe/v4/top/anime?filter=upcoming&limit=6')
      }, 1200)

      return res
    }

I can't return the value of setTimeout because that will always be the timerID. Currently res will always return undefined from the animeUpcomingFetcher call. How can I delay this fetch and return the result to the useQuery hook?

CodePudding user response:

React query has the concept of chaining requests, so if you have 4 API calls to make, but can only make 2 at a time, you can chain them so make sure you would ever only make 2 at once.

For example,

1 -> 3

2 -> 4

each number represent a single request. And you do that in react query using the enabled option.

const one = useQuery(['one'], fetcherFnOne);
const two = useQuery(['two'], fetcherFnTwo);

const three = useQuery(['three'], fetcherFnThree, { enabled: one.isSuccess });
const four = useQuery(['four'], fetcherFnFour, { enabled: two.isSuccess });

so now, three will only fire after one is done. Same for four and two.

https://tanstack.com/query/v4/docs/guides/dependent-queries

  • Related