T
TanStack4mo ago
generous-apricot

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 };
},
});
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)),
});
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);
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?
1 Reply
generous-apricot
generous-apricotOP4mo ago
i should note, my queryClient is created inside createRouter() after some debugging, it was the staleTime causing this issue. i don't mind removing that, but i'm curious why it would ever return null and cache? 🤷‍♂️

Did you find this page helpful?