next.jsreact-querytrpct3

'Unhandled Runtime Error' using TRPC's useQuery


I am trying to use the [id] paramether from my [id].tsx filename inside a TRPC query, but getting the error:

Unhandled Runtime Error
Error: Rendered more hooks than during the previous render.

This is because the 'id' paramether is unknown initially. I tried to disable my query by default by the 'enabled' flag from react query, but am still getting the same result.

import type { NextPage } from "next";

import Image from "next/image";
import { useSession } from "next-auth/react";
import { useRouter } from "next/router";
import { api } from "@/utils/api";
import { LoadingSpinner } from "@/components/loading";

const EvaluationPage: NextPage = () => {
  const { data: session } = useSession();
  const router = useRouter();
  const { id } = router.query;

  if (!id || Array.isArray(id)) return <LoadingSpinner />;

  const { data } = api.image.getEvaluation.useQuery(
    {
      id,
    },
    {
      enabled: false,
    }
  );

  return (
    <>
      <main className="flex min-h-screen flex-col items-center justify-center bg-gradient-to-br from-blue-400 to-indigo-800">
        {session ? (
          <div className="container flex flex-col items-center justify-center gap-12 px-4 py-12 ">
            <h1 className="font-base text-3xl tracking-tight text-gray-100 sm:text-3xl">
              Image evaluation
            </h1>

            <>{data && <p className="text-white">{data.response}</p>}</>
          </div>
        ) : (
          <div className="flex flex-col items-center justify-center gap-4 py-4">
            <h3 className="text-center text-2xl text-gray-100">
              Please sign in to continue.
            </h3>
          </div>
        )}
      </main>
    </>
  );
};

Does anyone have any advice of how to easiest solve this?


Solution

  • I got help from the TRPC discord channel where it was pointed out that it was the usage of a 'return' statement before a hook that caused the error.

    Removing that and modifying my trpc call to this did the trick!

    const { data } = api.image.getEvaluation.useQuery(
      { id: id as string },
      { enabled: !!id }
    );