Home > Software design >  react query with parameters
react query with parameters

Time:09-23

I have a react query that wraps on of my API calls. I would like to expose a paramter to the user of my custom hook which lets them set the paramter for this specific API call.

How can I do that idiomatically?

My current custom hook looks like this:

const useGamesApi = () => {
  const [games, setGames] = useState<Game[]>([]);

  const upcomingGamesQuery = useQuery(
    ["upcoming", date],
    async ({ queryKey }) => {
      const [_, date] = queryKey;

      const ret = await apiGetUpcomingGames(date);
      return ret;
    },
    {
      onSuccess: (data) => {
        setGames(data);
      },
    }
  );

  return {
    games: games,
  };
};

export default useGamesApi;

This doesn't expose the date parameter as I would want it, since there is no external way of modifyin that date parameter.

CodePudding user response:

You can just pass the parameter in braces, just like functions. Then user would be able to use it like useGamesApi(key)

  • Related