1

New to trpc. Trying to get basic query functionality but it's not working. Not sure what I'm missing. In v9 it used createReactQueryHooks(), but it seems in v10 you only need to use createTRPCNext() if I'm not mistaken inside util/trpc.tsx.

Error:

next-dev.js:32 Error: Query data cannot be undefined - affected query key: ["greeting"]
    at Object.onSuccess (query.mjs:320:19)
    at resolve (retryer.mjs:64:50)
// utils/trpc.ts
export const trpc = createTRPCNext<AppRouter, SSRContext>({
    config({ ctx }) {
        return {
            transformer: superjson, // optional - adds superjson serialization
            links: [
                httpBatchLink({
                    /**
                     * If you want to use SSR, you need to use the server's full URL
                     * @link https://trpc.io/docs/ssr
                     **/
                    url: `${getBaseUrl()}/api/trpc`,
                }),
            ],
            /**
             * @link https://react-query-v3.tanstack.com/reference/QueryClient
             **/
            // queryClientConfig: { defaultOptions: { queries: { staleTime: 60 } } },
            headers() {
                if (ctx?.req) {
                    // To use SSR properly, you need to forward the client's headers to the server
                    // This is so you can pass through things like cookies when we're server-side rendering
                    // If you're using Node 18, omit the "connection" header
                    const {
                        // eslint-disable-next-line @typescript-eslint/no-unused-vars
                        connection: _connection,
                        ...headers
                    } = ctx.req.headers;
                    return {
                        ...headers,
                        // Optional: inform server that it's an SSR request
                        "x-ssr": "1",
                    };
                }
                return {};
            },
        };
    },
    ssr: true,
});
// server/router/_app.ts
import { t } from '@/server/trpc';
import { userRouter } from '@/server/router/user';
import { postRouter } from '@/server/router/posts';
import { authRouter } from './authy';

export const appRouter = t.router({
    user: userRouter,
    post: postRouter,
    authy: authRouter,
    greeting: t.procedure.query(() => 'hello tRPC v10!'),
});

export type AppRouter = typeof appRouter;
// server/router/authy.ts
import { t } from "@/server/trpc";
import * as trpc from "@trpc/server";
import { z } from "zod";

export const authRouter = t.router({
    hello: t.procedure
        // using zod schema to validate and infer input values
        .input(
            z.object({
                    text: z.string().nullish(),
                })
                .nullish().optional()
        )
        .query(({ input }) => {
            return {
                greeting: `hello ${input?.text ?? "world"}`,
            };
        }),
});

export type AuthRouter = typeof authRouter;

None of the routes work. They all show a similar error.

// pages/test.tsx
import React from "react";
import { NextPage } from "next";
import { trpc } from "@/utils/trpc";

const TestPage: NextPage = () => {
    const helloNoArgs = trpc.authy.hello.useQuery();
    const helloWithArgs = trpc.authy.hello.useQuery({ text: "client" });
    const greeting = trpc.greeting.useQuery();

    return (
        <div>
            <h1>Hello World Example</h1>
            <ul>
                <li>
                    helloNoArgs ({helloNoArgs.status}):{" "}
                    <pre>{JSON.stringify(helloNoArgs.data, null, 2)}</pre>
                </li>
                <li>
                    helloWithArgs ({helloWithArgs.status}):{" "}
                    <pre>{JSON.stringify(helloWithArgs.data, null, 2)}</pre>
                </li>
                <li>
                    greeting ({greeting.status}):{" "}
                    <pre>{JSON.stringify(greeting.data, null, 2)}</pre>
                </li>
            </ul>
        </div>
    );
};

export default TestPage;

wongz
  • 3,255
  • 2
  • 28
  • 55

3 Answers3

3

It seems you are using superjson. You need to add superjson transformer at initTRPC.

routers/router/_app.ts

import { initTRPC } from '@trpc/server';
import superjson from 'superjson';
export const t = initTRPC.create({
  transformer: superjson,
});

more detailed instruction can be found here: TRPC v10

Suben Saha
  • 1,778
  • 16
  • 21
0

Omgosh... it was because I was using "^10.0.0-proxy-beta.7" and not "^10.0.0-proxy-beta.8"

Edit: Somehow I had another error and encountered my own question again 22 days later and solved it again. In general, when using trpc it seems updating to all the @next packages is best as it seems to be somewhat easy to have packages not talking to each other as they improve.

https://trpc.io/docs/v10/quickstart#installation-snippets

wongz
  • 3,255
  • 2
  • 28
  • 55
0

On my side I was using a mocked trpc server that was not using superjson (whereas the real one was). I just used superjson.serialize(...) before adding the JSON body to my response (in my server mock), then it worked :)

Thomas Ramé
  • 438
  • 4
  • 10