TanStackT
TanStack8mo ago
2 replies
inadequate-blush

QueryClient cache getting invalidated between navigation?

hello! running into a weird bug with my app. my currentUser state is managed in an isomorphic QueryClient, but it seems to return inconsistent behavior throughout the app. when i am logged in:

* visiting /chat correctly loads the active user from state
* visiting /chat, then visiting
/
, then reloading, then visiting /chat shows i am logged out! a simple refresh corrects the state.

i think my setup is pretty straight forward, so not sure where my misstep is:

i've got a root (__root.tsx) route defined as:

export const Route = createRootRouteWithContext<{
  queryClient: QueryClient;
  user: User | null;
}>()({
  component: RootComponent,
  beforeLoad: async ({ context }) => {
    await context.queryClient.prefetchQuery(userQueryOptions); // prefetch on the server to load user quickly
  },
  loader: async ({ context }) => {
    const user = await context.queryClient.ensureQueryData(userQueryOptions); // make sure auth state is resolved before first paint
    return { user };
  },
});


userQueryOptions looks like this:

export const userQueryOptions = queryOptions({
  queryKey: ["user"],
  queryFn: getCurrentUser, // this is a server function that returns the current user based on cookies
  staleTime: Duration.toMillis(Duration.hours(1)),
});


and i consume it with a basic hook:

export const useUser = () => useQuery(userQueryOptions);


my understanding is that the result of useUser should always be fresh between navigations as we call ensureQueryData. is this not correct?
Was this page helpful?