0

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, 
  });
};

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 2

0

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.

Sign up to request clarification or add additional context in comments.

8 Comments

Okay, here's what I want: When the deck value is available, I want to serve it from the getCards() query function using the state value. If it's not available, I want to make a network request to retrieve that data. However, the problem arises when, for example, you have a deck value and a user creates a new card. I set the deck value to null and invalidate this query using the useCreateCard hook, like this: queryClient.invalidateQueries({ queryKey: ["cards", mutationData.deck_id], }); This is to fetch the newly added card from the server. Continued in the next comment....
However, the issue is that initially, when useGetCards mounts, it has a deck value. Later, if you set it to null or anything else, it doesn't update; it still uses the initial value when you invalidate the query. I know that changing the query key creates a new cache and all, but my problem is that I want to keep the query key the same but just recreate the query function with the new deck value, which is null. This way, when a user creates a new card, it triggers a network request to fetch the newly created card. Continued in the next comment....
I'm implementing this to avoid unnecessary network calls when the required data is already in the state. So, please let me know if you know how to recreate a query function if you have some dependency that changes over time.
regarding this:I can't tell you why invalidateQueries doesn't work since...It invalidates the query, but it still uses the old query function with the initial deck value. Even when you update the deck value to null or anything else, it continues to use the initial value that was given when the useGetCards() hook mounted. If you look at my getCards() function, you'll notice it includes an if-else condition. So, if you have a deck value, it always runs the else condition; if you don't have a deck value, it always runs the if condition, even after invalidating the query with different deck value.
@MaxVhanamane see my extended answer
|
0

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, 
  });
};

export default useGetCards;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.