useQuery with tRPC wont recieve my query input

Viewed 695

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 :)

4 Answers

Try removing the .nullish part and adding a ':' after resolve like this:

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

I am also quite new to trpc so i'm sorry if this doesn't help.

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.

Ran into this issue on VSCODE. Quitting VS code, and reopening the project solved this (it also then properly showed any underlying issues).

I just had a similar problem and been poking and prodding it for two days.

Turns out it goes away once you set strict to true in the tsconfig.json under compilerOptions

The fragility of the TypeScript tool-chain never ceases to amaze me.

Related