T
TanStack2mo ago
other-emerald

Display general error message from server

How can we show a general (not linked to a specific field) error message from an API? We have a login api that throws an error but not on a specific field because we don't want the user to know which field is wrong (obviously).
const form = useAppForm({
validators: {
onSubmit: LoginRequest,
onSubmitAsync: async ({ value }) => {
try {
await login.mutateAsync(value)
return null
} catch (e) {
console.log(e)
return {
fields: {
password: { message: 'Invalid email or password' }
}
}
}
}
},
defaultValues: {} as LoginRequest,
onSubmit: () => {
navigate({ to: '/' })
},
});
const form = useAppForm({
validators: {
onSubmit: LoginRequest,
onSubmitAsync: async ({ value }) => {
try {
await login.mutateAsync(value)
return null
} catch (e) {
console.log(e)
return {
fields: {
password: { message: 'Invalid email or password' }
}
}
}
}
},
defaultValues: {} as LoginRequest,
onSubmit: () => {
navigate({ to: '/' })
},
});
This now shows the error on the password field, But i rather dont want to do that and set it on 'server' for example and show that message. I have found that other people handle this state outside of the form with just a simple const [error, setError] = useState() and set that error but what do i return in the catch? because i need to return some error in the onSubmitAsync to actually stop the from from handling onSubmit
2 Replies
other-emerald
other-emeraldOP2mo ago
I already find it really weird that we basically forcing the mutation already in the validators (yes it handles validation as well). It would be imo way more intuitive if we could set errors outside of validators as well so we could do
onSubmit: () => {
login.mutateAsync(form.state.values).catch((e) => {
// Set field errors somehow
// return {
// fields: {
// password: { message: 'Invalid email or password' }
// }
// }
// Set general error
});
},
onSubmit: () => {
login.mutateAsync(form.state.values).catch((e) => {
// Set field errors somehow
// return {
// fields: {
// password: { message: 'Invalid email or password' }
// }
// }
// Set general error
});
},
rival-black
rival-black2mo ago
From the Form Validation Docs:
// Combining form-level errors and field-level errors
return {
form: 'Invalid data', // The `form` key is optional. This is the general error
fields: {
username: "Problem"
}

// Just any form-level error
return "Invalid data"
// Combining form-level errors and field-level errors
return {
form: 'Invalid data', // The `form` key is optional. This is the general error
fields: {
username: "Problem"
}

// Just any form-level error
return "Invalid data"
as for setting errors in onSubmit, it's currently being discussed. One issue it has is that (as you see it too), making it intuitive is hard, but it would be nice to return it somehow.

Did you find this page helpful?