TanStackT
TanStackโ€ข3mo agoโ€ข
9 replies
skinny-azure

How to initialize query from within a loader using data from another query?

Hey there ๐Ÿ‘‹ I am currently trying to figure out how to initialize a query using data from another query within a route loader in Start. I was unsure if this Q belonged in #start-questions , #react-query-questions , or #router-questions , so if this is the wrong place I'd be glad to remove it and ask elsewhere.

I originally tried ensureQueryData with initialData but this wasn't working for me. So, I figured, maybe manually setting it ๐Ÿคทโ€โ™‚๏ธ But because route loaders in Start are isomorphic this can't be right + it doesn't work...
export const Route = createFileRoute("/_main/teacher/$teacherSlug")({
  loader: async ({ context, params }) => {
    const teacher = await context.queryClient.ensureQueryData(
      api.teachers.findProfileBySlug.queryOptions({
        input: {
          slug: params.teacherSlug,
        },
      }),
    );

    teacher &&
      context.queryClient.setQueryData(
        api.teachers.getSave.queryKey({
          input: {
            teacherId: teacher.id,
          },
        }),
        () => ({
          isSaved: !!teacher.saves?.length,
          savedAt: teacher.saves?.[0]?.createdAt || null,
          teacherId: teacher.id,
          saveId: teacher.saves?.[0]?.id || null,
        }),
      );
    return {
      dehydratedState: dehydrate(context.queryClient),
    };
  },
  component: TeacherPage,
});

function TeacherPage() {
  const { dehydratedState } = Route.useLoaderData();
  // ...
  return (
    <HydrationBoundary state={dehydratedState}>{/** ... */}</HydrationBoundary>
  );
}

function SomeRandomComponentSomewhere({ teacherId }: { teacherId: string }) {
  const { data: saveState } = useQuery(
    // Query should be initialized
    api.teachers.getSave.queryOptions({
      input: {
        teacherId,
      },
    }),
  );

  return <div>SSR initialized save state: {JSON.stringify(saveState)}</div>;
}


If anyone has any suggestions on what to do here, I'd greatly appreciate it!
Was this page helpful?