TanStackT
TanStack12mo ago
4 replies
full-green

Question about ensureQueryData

I have the following beforeLoad in tanstack router

export const Route = createFileRoute("/_auth")({
  beforeLoad: async ({ context, location }) => {
    if (!context.user) {
      throw redirect({
        to: "/login",
        search: {
          redirect: location.href,
        },
      });
    }

    const { onboarding } = await context.queryClient.ensureQueryData(onboardingQueryOptions(context.user.id));
    console.log(onboarding);

   return {
      user: context.user,
    };
}


On the queryClient i have a default staleTime: 1000 * 20, of 20 seconds. I noticed that the onboarding variable doesn't update if i navigate to a different page in the same _auth layout after 20 seconds. If there is data in the query cache, it will never fetch new data even if it is stale?

Switching to:
const { onboarding } = await context.queryClient.fetchQuery(onboardingQueryOptions(context.user.id));


Seems to take in consideration the staleTime

Thank you!

(Notice i do not use that query in another place. I saw that if i also have a "useSuspenseQuery" in combination with the ensureQueryData in the loader for different api calls, that one works. So i guess the useSuspenseQuery invalidates ( triggers a refetch ) if the query is stale )
Was this page helpful?