TanStackT
TanStack2y ago
6 replies
broad-emerald

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}</>
}
image.png
Was this page helpful?