skip to Main Content

I’m encountering an issue where the useQuery hook in React Query doesn’t update its query function when certain data changes. Here’s my code:

import { request } from "../utils/fetch-utils";
import { useQuery } from "@tanstack/react-query";
import { CustomError } from "../utils/customError";
import { useCallback, useContext } from "react";
import { OfflineContext } from "../context/OfflineContext";
import { DeckTypeForSearch } from "../types/types";

type SuccessResponseType = {
  title: string;
  cards: { title: string; note: string; cardId: string; _id: string }[];
  _id: string;
};

const getCards = async (
  _id: string,
  deck: DeckTypeForSearch | null
): Promise<SuccessResponseType | null> => {
  if (!deck) {
    try {
      const data = await request.get(`/cards/${_id}`);
      return data?.data;
    } catch (error) {
      if (error instanceof CustomError) {
        // Now TypeScript recognizes 'error' as an instance of CustomError
        throw new CustomError(error?.message, error?.statusCode);
      } else {
        throw new CustomError("Something went wrong!", 503);
      }
    }
  } else if (deck) {
    return { title: deck.title, cards: deck.cards, _id: deck.deck_id };
  }

  return null;
};

const useGetCards = (deck_id: string) => {
  const { deck } = useContext(OfflineContext);


  const queryKey = ["cards", deck_id];
  const getDataCallbackFunction = useCallback(() => {
    return getCards(deck_id, deck);
  }, [deck, deck_id]);

  return useQuery({
    queryKey: queryKey,
    queryFn: () => {
      return getDataCallbackFunction();
    },

    refetchOnWindowFocus: false, // Don't refetch on window focus
    refetchOnReconnect: true, // Refetch on network reconnect
    retry: 0, // no retry on network errorMessage
    gcTime: 10800000, // 3 handleShowUserInfomation
  });
};

export default useGetCards;

Suppose the initial value of deck is { title: "My title", cards: "my cards", _id: "my id" }. When the deck value changes, for example, to null, and I invalidate the query using queryClient.invalidateQueries,

 queryClient.invalidateQueries({
        queryKey: ["cards", mutationData.deck_id],
      });

it seems that the query function getCards(deck_id, deck) still uses the initial value of deck which is { title: "My title", cards: "my cards", _id: "my id" } instead of null. I’ve tried recreating the function using useCallback, but it still uses the old deck value. I want the query function to receive the updated deck value whenever it changes, but this isn’t happening. Is there a way to ensure that the query function is recreated with the latest data?
The query key remains the same, but the data passed to the query function will vary.
so this solution won’t work Link

Version- "@tanstack/react-query": "^5.10.0",

2

Answers


  1. Chosen as BEST ANSWER

    This solution works as expected, for better understanding see the discussion in the comments section of Anton's answer.

    import { request } from "../utils/fetch-utils";
    import { useQuery } from "@tanstack/react-query";
    import { CustomError } from "../utils/customError";
    import { useContext } from "react";
    import { OfflineContext } from "../context/OfflineContext";
    
    type SuccessResponseType = {
      title: string;
      cards: { title: string; note: string; cardId: string; _id: string }[];
      _id: string;
    };
    
    const getCards = async (_id: string): Promise<SuccessResponseType | null> => {
      try {
        const data = await request.get(`/cards/${_id}`);
        return data?.data;
      } catch (error) {
        if (error instanceof CustomError) {
          // Now TypeScript recognizes 'error' as an instance of CustomError
          throw new CustomError(error?.message, error?.statusCode);
        } else {
          throw new CustomError("Something went wrong!", 503);
        }
      }
    };
    
    const useGetCards = (deck_id: string) => {
      const { deck } = useContext(OfflineContext);
      const queryKey = ["cards", deck_id];
    
      return useQuery({
        queryKey: queryKey,
        queryFn: () => {
          return getCards(deck_id);
        },
        enabled: !deck,
        initialData: deck
          ? { title: deck.title, cards: deck.cards, _id: deck.deck_id }
          : undefined,
    
        refetchOnWindowFocus: false, // Don't refetch on window focus
        refetchOnReconnect: true, // Refetch on network reconnect
        retry: 0, // no retry on network errorMessage
        gcTime: 10800000, // 3 handleShowUserInfomation
      });
    };
    
    export default useGetCards;
    

  2. The query key remains the same, but the data passed to the query function will vary.

    This is not how query keys are designed to work. From the docs:

    As long as the query key is […] unique to the query’s data, you can use it!

    So if you want to go with this approach you need to pass in deck or the deck data to the query key as well.

    However I would move the deck dependency out of getCards so that useQuery only runs when there is a need to fetch data. useQuery shouldn’t be concerned with caching something that is already "cached" by OfflineContext.

    const useGetCards = (deck_id: string) => {
      const { deck } = useContext(OfflineContext);
    
      const queryKey = ["cards", deck_id];
    
      const runQuery = !deck;
    
      const query = useQuery({
        queryKey: queryKey,
        queryFn: () => getCards(deck_id),
    
        refetchOnWindowFocus: false, // Don't refetch on window focus
        refetchOnReconnect: true, // Refetch on network reconnect
        retry: 0, // no retry on network errorMessage
        gcTime: 10800000, // 3 handleShowUserInfomation
    
        // disable query if deck is present
        enabled: runQuery,
      });
    
      return {
        // either return data from query or context
        data: runQuery ? query.deck : deck,
        // error from query is probably useful for consumers
        error: query.error,
        ...{
          // other properties from query that are useful for consumers
        },
      };
    };
    

    I can’t tell you why invalidateQueries doesn’t work since you didn’t show when it is used. But I would expect it to work as you described.

    UPDATE AFTER COMMENTS

    I understand your issue better now, but I still believe the suggested code would fix your issue in a good way: A network request is only made when there is no state value, otherwise the state value is returned.

    Updating the query function sounds error-prone to me and that is not how Tanstack Query is designed to work. Further on, I don’t see the behavior you mention, that the query function uses an outdated value. This is neither how Javascript works generally even though React makes it more complicated. I’m guessing you are seeing this behavior due to race conditions in the context and query cache, e.g. if the query is invalidated before the context is null, the query will cache the old value again. Which is one reason why I think it’s a bad approach.

    One other approach that might solve you issue is using initial data.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search