Search code examples
reactjstypescriptreact-hooksreact-typescripttrpc.io

useQuery with tRPC wont recieve my query input


I am new to tRPC and react-query. I've been working to test .query (BE) and useQuery (FE) and I tried to pass data from FE to BE. However, since TS is a static typing, I get compile error although the code is working (it's working smoothly if I change to JS).

Here's my BE

export const appRouter = trpc
  .router()
  .query("greet", {
    input: z
      .object({
        name: z.string().nullish(),
      })
      .default({ name: "World" }),
    resolve({ input }) {
      return {
        message: `Hello ${input.name?.toUpperCase()}!`,
      };
    },
  })

and my FE is calling it by

const greet = trpc.useQuery(["greet", { name: "Maria" }]);

The compile error is on the { name: "Maria" } part.

It says "Type '{ name: string; }' is not assignable to type 'null | undefined'.ts(2322)". I don't know why the useQuery type definition is like this. Which I think I can't pass any parameters at all(?)

Please help, I have no idea. Thanks for reading and answering my question :)


Solution

  • A little bit of update, I have resolved this problem by moving to a new repo, lol.

    I think the problem is possibly caused by

    Possibility 1: The undefined createReactQueryHooks in the "trpc" so you need to specify const trpc = new createReactQueryHooks<AppRouter>(); with the AppRouter being the appRouter type you export from the BE. Don't do const trpc = new createReactQueryHooks(); with "any" type.

    Possibility 2: Your javascript and typescript package overlaps, so the compiler might mistakenly detect the javascript one which most of them do not specify type.