TanStackT
TanStack16mo ago
12 replies
forward-apricot

getQueryData returning undefined unless exact key match

I am trying to use one cache as the initial value for another, following https://tanstack.com/query/latest/docs/framework/react/guides/initial-query-data#initial-data-from-cache

Example code
const useCustomHook = (param) => {
  const queryClient = useQueryClient();

  const query = useQuery({
    queryKey: ['key', param],
    queryFn: async () => {
      return await fetchData();
    },
    initialData: () => {
      console.log('init', queryClient.getQueryData(['key']));
      return undefined;
    },
  });

  console.log('root', queryClient.getQueryData(['key']));

  return query
}


Both the
init
and
root
logs are
undefined
I understand on the initial query there is no data and I would expect undefined, but on changing param I still get undefined. But if I update the logs to queryClient.getQueryData(['key', param]) the cached data is returned.

Am I missing a something, the docs say I should be able to get the data with only a partial key match
Headless, type-safe, powerful utilities for complex workflows like Data Management, Data Visualization, Charts, Tables, and UI Components.
TanStack | High Quality Open-Source Software for Web Developers
Preview image
Was this page helpful?