TanStackT
TanStack9mo ago
36 replies
comprehensive-tomato

ensureQueryData on loader breaks page.

Getting this error on the client console:
TRPCClientError: Unexpected token '<', "<!DOCTYPE html>" is not valid JSON

The loader uses ensureQueryData to use it as the page title:

export const Route = createFileRoute('/_authed/_appLayout/posts/$postId')({
  loader: async ({ params: { postId }, context }) => {
    const post = await context.queryClient.ensureQueryData(
      context.trpc.post.getPost.queryOptions({ id: postId })
    );

    if (!post) {
      throw notFound();
    }

    return post;
  },
  head: ({ loaderData }) => ({
    meta: [
      {
        title: loaderData.title ?? 'Untitled',
      },
    ],
  }),


If I remove the ensureQueryData it works by fetching the same on the client:

function PostComponent() {
  const params = Route.useParams();

  const trpc = useTRPC();

  const postQuery = useSuspenseQuery(
    trpc.post.getPost.queryOptions({ id: params.postId })
  );

  return (
    <>
      <p>query data: {JSON.stringify(postQuery.data.id)}</p>
    </>
  );
}
image.png
Was this page helpful?