How to use the useQueries hook in react-query v4

Viewed 44

So I'm perfectly able to retrieve matches from a competition with the Football-data.org API and display them in my react/typescript application using the useQuery hook from react-query:

import {CompetitionProps} from "../App";
import {getMatchesFromApi, Match} from "../api/GetMatchesFromApi";
import {List, ListItem} from "@mui/material";
import {useQuery} from "@tanstack/react-query";

function MatchesList({competitions}: CompetitionProps) {
    const { isLoading, error, data, isFetching} = useQuery(["matches"], async () => {
        return await getMatchesFromApi(competitions);
    });

    if (isLoading || isFetching) {
        return (<div>Loading</div>);
    } else {
        return (
            <List>
                {data?.map((match: Match) => {
                   return (
                       <ListItem key={match.id}>{match.homeTeam.shortName} - {match.awayTeam.shortName}</ListItem>
                   );
                })}
            </List>
        );
    }
}

export default MatchesList;

However I want all matches from a list of competitions (the competitions can be different based on user preferences). When reading the docs of react-query, the useQueries hook should do the trick. These docs unfortunately don't show how to handle the results of the useQueries hook: https://tanstack.com/query/v4/docs/reference/useQueries

I tried to use it like this:

import {
  useQueries,
  UseQueryOptions,
  UseQueryResult
} from "@tanstack/react-query";
import { getMatchesFromApi, Match } from "./GetMatchesFromApi";

const allCompetitions = [2003, 2021];

function MatchesList() {
  const results = useQueries({
    queries: allCompetitions.map<UseQueryOptions<Match[]>>(
      (competition: number) => {
        return {
          queryKey: ["competition", competition],
          queryFn: async () => await getMatchesFromApi(competition)
        };
      }
    )
  });

  return <div>{results.length}</div>;
}

export default MatchesList;

Even though I'm not even attempting to display the data yet, just using this code that only prints the length of the results array, will cause the code to fetch every few seconds. This will result in 429 (too many requests) responses of the football-data.org API fairly quickly.

enter image description here

This behavior doesn't match at all with the default staleTime and cacheTime settings explained in: https://medium.com/doctolib/react-query-cachetime-vs-staletime-ec74defc483e

The question: How do I stop this infinite fetching loop? The reason I wanted to use react-query at all is to lazy fetch the match data only once.

Full project to reproduce this problem: https://codesandbox.io/s/serene-raman-47n2uz

(If you want to reproduce it, you'll have to register on football-data.org for free and generate an API key. Put your key in the Key.ts file. I don't want to put mine on the internet).

Thanks!

0 Answers
Related