react query returning empty object for data

Viewed 26

I am trying to abstract away my react/tanstack query.

I have a custom hook like the following:

const useGamesApi = () => {
  const upcomingGamesQuery = useQuery(
    ["upcoming", date],
    async () => {
      const ret = await apiGetUpcomingGames(date);
      return ret;
    },
    {
      onSuccess: (data) => {
        setGames(data);
      },
    }
  );

  return {
    games: upcomingGamesQuery,
  };
};

export default useGamesApi;

I am trying to consume my API as follows:

const [games, setGames] = useState<Game[]>([]);
const gamesApi = useGamesApi();
useEffect(() => {
    setGames(gamesApi.games.data);
  }, []);

This leads to compilation errors and also the value of my games state variable remains an empty array, as if the useEffect never ran.

Basically I am trying to abstract away my react query to provide a simplified way of interacting with it for my components, whilst also giving it a chance to modify the parameter of the date, so that I can be able to set until which date I would like to query.

What would be the correct (compilation vise) and idiomatic way of doing this with react?

(note I am using this in a react native project, not sure if it counts.)

1 Answers
  1. As per rules , You need to add all the variables used inside useEffect as dependency so that it reacts once the value is changed.

  2. You don't really need useEffect for you scenario. It is used to cause side effects. simply do it like :

 const games: Game[] = gamesApi?.games?.data;
  
  const games: Game[] = gamesApi?.games?.data || []; // incase you need default value
Related