reactjsreact-querytanstacktanstackreact-query

How to invalidate cache initialData in react query/tanstack query?


I am using useQuery hook in TanStack Query (previously React Query) to cache data, in my case I config initialData depend on another hook useInfiniteQuery but when I am trying to invalidate useInfiniteQuery, cache from useQuery always immutate. In the following code below, the reason I do this way is because of my own intentions. Is there a way to force initialData to receive new data that depends on item ?

Post list component:

const queryClient = useQueryClient();
const { data } = useInfiniteQuery({ queryKey: ['posts'], ... });

const flatten = useMemo(() => data && data.pages.map((page) => page).flat(), [data]);

return (
   <>
     {flatten.map(post => (
        <Post key={post.id} item={post} />
     ))}

     // invalite cache from useInfiniteQuery to receive new cache
     <button onClick={() => queryClient.invalidateQueries({ queryKey: ['posts'] })}>
        Invalidate post
     </button>
   </>
)

Post component:

function Post ({ item }) {
  const { data } = useQuery({ 
    queryKey: ['post', item.id], 
    queryFn: getPost,
    enabled: !!item.id,
    initialData: item
  });

  // always get old cache data although value of item is mutated

  return <pre>{JSON.stringify(data)}</pre>;
}

Solution

  • query invalidation will re-run the QueryFunction, it has no effect on initialData. initialData is only used to fill the cache "initially" (once) if it has no data yet.

    if you want to synchronously update the Query, use queryClient.setQueryData