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
This solution works as expected, for better understanding see the discussion in the comments section of Anton's answer.
This is not how query keys are designed to work. From the docs:
So if you want to go with this approach you need to pass in
deck
or thedeck
data to the query key as well.However I would move the
deck
dependency out ofgetCards
so thatuseQuery
only runs when there is a need to fetch data.useQuery
shouldn’t be concerned with caching something that is already "cached" byOfflineContext
.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.