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
hutajoullach
hutajoullach15mo ago
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 }) }
Yosif Stalin Gaming
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
deforestor
deforestor15mo ago
that is done here:
const onSubmit = () => {
mutate({
calories: cals + formData.calories,
protein: rawUserStats.protein + formData.protein,
carbs: rawUserStats.carbs + formData.carbs,
fats: rawUserStats.fat + formData.fat
})
}
const onSubmit = () => {
mutate({
calories: cals + formData.calories,
protein: rawUserStats.protein + formData.protein,
carbs: rawUserStats.carbs + formData.carbs,
fats: rawUserStats.fat + formData.fat
})
}
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:
const { mutate, isLoading } = api.user.updateUserStats.useMutation()
const { mutate, isLoading } = api.user.updateUserStats.useMutation()
and then the
// your input in the {...}
mutate({...})
// your input in the {...}
mutate({...})
Yosif Stalin Gaming
Thanks
Want results from more Discord servers?
Add your server
More Posts