tRPC useQuery() or useMutation()

I have a component with a form containing a question about a secret name. When submitting that form I want to validate that the user sent the correct secret name. What should I use? (the name will be in my environment variables) Im currently trying to implement it with useMutation(). Is this the correct method to use? This is what I have so far:
const { mutate } = api.userRouter.checkCatName.useMutation();
const handleSubmit = (values: { catName: string }) => {
const res = mutate(values);
console.log(res);
};
const { mutate } = api.userRouter.checkCatName.useMutation();
const handleSubmit = (values: { catName: string }) => {
const res = mutate(values);
console.log(res);
};
its currently working, but i cant f.ex do console.log(res.result) I then get an error Cannot read properties of undefined. This is the procedure code:
checkCatName: protectedProcedure
.input(z.object({ catName: z.string().min(1).max(20) }))
.mutation(({ input }) => {
if (input.catName === 'secret') {
return 'you did it!';
}
return 'you are bad';
}),
checkCatName: protectedProcedure
.input(z.object({ catName: z.string().min(1).max(20) }))
.mutation(({ input }) => {
if (input.catName === 'secret') {
return 'you did it!';
}
return 'you are bad';
}),
2 Replies
JulieCezar
JulieCezar15mo ago
The first part isn't really the best... Do this instead
const { mutate } = api.userRouter.checkCatName.useMutation({
onSuccess: (data) => {
console.log(data)
},
onError: (err) => {
console.log(err)
}
});
const handleSubmit = (values: { catName: string }) => {
mutate(values);
};
const { mutate } = api.userRouter.checkCatName.useMutation({
onSuccess: (data) => {
console.log(data)
},
onError: (err) => {
console.log(err)
}
});
const handleSubmit = (values: { catName: string }) => {
mutate(values);
};
mutations are async, so you would need to await the response and RQ lets you can define callback functions for such events, like in the example above onSuccess and onError you have many more, as well as additional config you can check out in the docs
sommeeeR
sommeeeROP15mo ago
Alright I try it out. Using mutation is ok tho?
Want results from more Discord servers?
Add your server