Call post.hello on button click

Hi, I know that trpc is using React useQuery under the hood in T3 on the client and therefore can only be used in a React component body. But, I am wondering if there is a way to modify the router call a trpc procedure on a button click in a client component.
import { api } from "~/trpc/react";
...
const handleHello = async () => {
const hello = await api.post.hello.query({ text: "from tRPC" });

};
....
<button onClick={handleHello}>Hello</button>
import { api } from "~/trpc/react";
...
const handleHello = async () => {
const hello = await api.post.hello.query({ text: "from tRPC" });

};
....
<button onClick={handleHello}>Hello</button>
I realize that I can make a fetch request to http://localhost:3000/api/trpc/post.test, but this defeats the point of TRPC.
4 Replies
andersgee
andersgee11mo ago
your trpc router should look something like hello: publicProcedure.input(...).mutation(()=>{...}) and the usage in your component looks something like
const postHello = api.post.hello.useMutation()
...
<button onClick={()=>postHello.mutate(...)}>
const postHello = api.post.hello.useMutation()
...
<button onClick={()=>postHello.mutate(...)}>
james162861
james162861OP11mo ago
thanks @andersgee, that did allow me to call the procedure on the button click. However, when I try to return data from the mutation, the return type is always void, even when I specify the output like so.
hello: publicProcedure
.input(z.object({ text: z.string() }))
.output(z.object({ greeting: z.string() }))
.mutation(({ input }) => {
console.log("calling server ");
return {
greeting: `Hello ${input.text}`,
};
}),
hello: publicProcedure
.input(z.object({ text: z.string() }))
.output(z.object({ greeting: z.string() }))
.mutation(({ input }) => {
console.log("calling server ");
return {
greeting: `Hello ${input.text}`,
};
}),
I cannot log the output
const handleStart = () => {
const result = postHello.mutate({ text: "from tRPC" });
console.log( result);
};
const handleStart = () => {
const result = postHello.mutate({ text: "from tRPC" });
console.log( result);
};
The procedure is definitely called though. I see "calling server" in the terminal
andersgee
andersgee11mo ago
The output will be in useMutation({onSuccess: (x)=>
james162861
james162861OP11mo ago
gotcha. Ok I need to read up on React Query. Thanks so much @andersgee
Want results from more Discord servers?
Add your server