TanStackT
TanStack8mo ago
24 replies
conventional-black

routerWithQueryClient: Invalidating queryClient cache

I'm running into an issue with client-side cache invalidation when using routerWithQueryClient.

Problem:
I have a loader that prefetches data on the server:

loader: async ({ params, context }) => {
  const { slug } = params
  const [member, organization] = await Promise.all([
    context.queryClient.ensureQueryData(getSelfQueryOptions()),
    context.queryClient.ensureQueryData(getSelfOrganizationQueryOptions()),
  ])
  return { member, organization }
}


The server fetch works, and I assume the cache is hydrated on the client automatically.

Later, on the client, after updating member, I try to invalidate the cached query:

const { mutate, isPending } = useMutation({
  mutationFn: useServerFn(updateSelfServerFn),
  onSuccess: async (memberEntity: Member) => {
    const slug = organization.stytch.organization_slug

    // Trying to invalidate query
    await queryClient.invalidateQueries({
      queryKey: queryKeys.getSelf(),
    })
  },
})


Core question:
Is useQueryClient the correct way to access the query client that routerWithQueryClient provides, or is there a better way to get the same instance that's being used by the router?

(when I navigate back to that original page that fetches member/org, its returning stale data instead of refetching first)
Was this page helpful?