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”,