TanStackT
TanStack7mo ago
3 replies
slow-yellow

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: '/' })
    },
  });

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
Was this page helpful?