T
TanStack4mo ago
adverse-sapphire

Handling server errors coming from `useMutation`

What is the best way to show Tanstack Query mutation errors with Tanstack Form? @Vincent asked the same question before in the form channel https://discord.com/channels/719702312431386674/1100437019857014895/1352359813853483132
1 Reply
adverse-sapphire
adverse-sapphireOP4mo ago
I think the main problem is that there is a mismatch between the standarSchema returned error types and the return type of validators.onSubmitAsync and also the mutateAsync throwes the error instead of returning it. And something like this (similar to what Vincent did) causes a lot of boilerplate:
validators: {
onSubmitAsync: async ({ value }) => {
try {
await otpSigninMutation.mutateAsync({
username: value.username,
otp: value.otp,
});
return null;
} catch (error) {
if (isTRPCClientError(error)) {
let fields: Record<string, { message: string }[] | undefined> = {};
const fieldErrors = error.data?.zodError?.fieldErrors;
for (const key in fieldErrors) {
fields[key] = fieldErrors[key]?.map((e) => ({
message: e,
}));
}
return { fields };
}
}
},
},
validators: {
onSubmitAsync: async ({ value }) => {
try {
await otpSigninMutation.mutateAsync({
username: value.username,
otp: value.otp,
});
return null;
} catch (error) {
if (isTRPCClientError(error)) {
let fields: Record<string, { message: string }[] | undefined> = {};
const fieldErrors = error.data?.zodError?.fieldErrors;
for (const key in fieldErrors) {
fields[key] = fieldErrors[key]?.map((e) => ({
message: e,
}));
}
return { fields };
}
}
},
},

Did you find this page helpful?