How to sent a mutation procedure from the client
updateUserStats:protectedProcedure
.input(z.object({
id:z.string().nonempty(),
protein:z.number().int(),
carbs:z.number().int(),
fats:z.number().int(),
calories:z.number().int(),
}))
.mutation(({ctx,input}) => {
const {id,protein,carbs,fats,calories} = input;
return ctx.prisma.foodStats.update({
where:{
userId:id
},
data:{
protein,
carbs,
fats,
calories
}
})
})
if thats the backend function how should i send a req from the client
api.user.updateUserStats.useMutation({
data:{
calories:cals + formData.calories,
protein:rawUserStats.protein + formData.protein,
carbs:rawUserStats.carbs + formData.carbs,
fats:rawUserStats.fat + formData.fat
},
})
something like this
4 Replies
on client side, you have access to mutate from useMutation, so you can mutate it in your submit func. you can clear useState or do other stuff inside onSuccess, onError as well.
const { mutate, isLoading } = api.user.updateUserStats.useMutation({
onSuccess: () => {
do something
},
onError: () => {
do something
},
});
const onSubmit = () => {
mutate({
calories: cals + formData.calories,
protein: rawUserStats.protein + formData.protein,
carbs: rawUserStats.carbs + formData.carbs,
fats: rawUserStats.fat + formData.fat
})
}
Can you explain a bit more. Sorry I am new to T3, but how to actually send the data that will be used for the mutation.I mean how does mutate know to mutate user.something
Also is there a docs where this is explained
that is done here:
mutate will call the procedure you made in the router.
I recommend you try React Query for a day, you'll understand everything
But in case you don't want to, the explanation is that React Query gives you all the tedious stuff from an API call, for example,
isLoading
, isError
, status.code
, etc.
In the case of mutations, it also returns you a method (mutate)
that calls your api (your tRPC procedure) with the input you declared on .input
Hence why you do:
and then the
Thanks