T
TanStack17mo ago
stormy-gold

useSuspenseQuery gets called although `loader` already fetched the data.

Hello everyone. I'm curious that this is the default behavior or I'm missing something? I follow the guide A more realistic example using TanStack Query in External Data Loading section in router docs. When I go to the page, ensureQueryData in loader gets called to fetch the data. After data is fetched, component is rendered. I expect that useSuspenseQuery in the component will use data that loader already fetched from the cache. Turns out it doesn't. useSuspenseQuery gets called to fetch the data again. This is the first time I use this approach. If I was wrong, please fix me. Thank you so much!!
export const Route = createFileRoute("/_authenticated")({
beforeLoad: ({ context, location }) => {
if (!context.auth.isAuthenticated) {
throw redirect({
to: "/auth/login",
search: {
redirect: location.href,
},
});
}

return {
user: context.auth.user,
};
},
component: Home,
loader: async (opts) =>
opts.context.queryClient.ensureQueryData(walletQueryOptions),
pendingComponent: () => <div>Loading...</div>,
});

function Home() {
const { data } = useSuspenseQuery(walletQueryOptions);

return <>{data}</>
}
export const Route = createFileRoute("/_authenticated")({
beforeLoad: ({ context, location }) => {
if (!context.auth.isAuthenticated) {
throw redirect({
to: "/auth/login",
search: {
redirect: location.href,
},
});
}

return {
user: context.auth.user,
};
},
component: Home,
loader: async (opts) =>
opts.context.queryClient.ensureQueryData(walletQueryOptions),
pendingComponent: () => <div>Loading...</div>,
});

function Home() {
const { data } = useSuspenseQuery(walletQueryOptions);

return <>{data}</>
}
No description
3 Replies
xenial-black
xenial-black17mo ago
Query automatically dedupes these requests, unless your queryKeys are changing or your staleTime is really low, you should only be firing off a single request. If you got a reproduction, it'd help figure out whats going on.
stormy-gold
stormy-goldOP17mo ago
Thanks for replying. I figured out the problem and fixed it. The problem is that I wrapped my App with two QueryClientProvider That's why it gets fetched twice. Just remove one of them and it works!
like-gold
like-gold17mo ago
What's your staleTime setting ? Ah okay, saw that you fixed it already

Did you find this page helpful?