T
TanStack11mo ago
exotic-emerald

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,
};
}
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));
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 )
3 Replies
exotic-emerald
exotic-emeraldOP11mo ago
Nvm…it seems I found the reason in the docs. Sorry for the stupid question Will leave this here if anybody faces the same misunderstanding
exotic-emerald
exotic-emeraldOP11mo ago
No description
exotic-emerald
exotic-emeraldOP11mo ago
You can pass revalidateIfStale: true for that

Did you find this page helpful?