TanStackT
TanStack3y ago
27 replies
primary-violet

Is a query not supposed to be generated upon page refresh?

I've observed this behavior where navigation from Page 1 to Page 2 adds the desired queries to the query cache, such that mutations that invalidate the target queries results in the desired refetches.
However, if I refresh Page 2, which calls custom hooks that in turn call useQuery, and then call the mutation method, the queries never appear in the cache to be invalidated, and therefore no refetch happens.

Is this expected behavior? Is there a way to resolve the difference in behavior between navigation and page refresh? Thank you in advance.

The custom hook that implements the useQuery call:
hooks/useGetIndividuals.tsx
...
import { QueryFunctionContext, useQuery } from "@tanstack/react-query";

export default function useGetIndividuals(collectionUrl: string) {
  const [errorMsg, setErrorMsg] = useState<string>("");
  const queryKey: [string, string] = ["individualsFor", collectionUrl];
  const { isLoading, isError, data } = useQuery({
    queryKey: queryKey,
    queryFn: async (context: QueryFunctionContext<[string, string]>) => {
      const [, collectionUrl] = context.queryKey;
      try {
        const response = await axios.get(
          "/api/collection/" + collectionUrl + "/individuals"
        );
        return response?.data?.individuals || [];
      } catch (e: any) {
         ...
        setErrorMsg(e.message);
      }
    },
  });

  return { isLoading, isError, data, errorMsg };
}


The component that employs said hook:
pages/collection/[urlPath]/index.tsx

...
const CollectionView: React.FC = () => {
  const queryClient = useQueryClient();
  ...
  const {
    isLoading: isLoadingIndividuals,
    isError: isErrorIndividuals,
    data: individualsData,
    errorMsg: errorMsgIndividuals,
  } = useGetIndividuals(localUrlPathAsString);
  ...
};
export default CollectionView;
Was this page helpful?