#Idiomatic approach to error handling when `onSubmit` handler rejects?

3 messages · Page 1 of 1 (latest)

teal bronze
#

This has very likely been asked before but couldn't find existing conversations about it. The most relevant example (https://tanstack.com/form/latest/docs/framework/react/examples/query-integration) also doesn't cover this.

I'm using @tanstack/react-query so I have something like this for the form setup:

const someMutation = useMutation(...)
const form = useForm({
  ...,
  onSubmit: async () => {
    return someMutation.mutateAsync(...)
  },
})

What's the recommended approach for reactively triggering some UI (e.g. an error dialog) when the onSubmit throws?

My initial inclination was to make use of someMutation.status i.e.

<ErrorDialog open={someMutation.status === 'error'} onClose={() => someMutation.reset()} />

Guessing that this would work fine in this specific case but wondering if there's something in the form store that I can subscribe to in order to achieve something similar?

#

My question is also more relevant for cases where query isn't being used.

dusk hazel
# teal bronze This has very likely been asked before but couldn't find existing conversations ...

It depends on who's at fault.

If you want to blame the user (e. g. prevent another submission until something has changed), then the request should be made in validators.onSubmitAsync. If there was an error, return that error. Otherwise, return nothing to indicate it was successful.

If the endpoint isn't a validator and errors can just happen (e. g. 500 errors), then the only requirement is that it's asynchronous and can throw (so that TanStack Form knows it wasn't a successful submission after all). The user won't be blamed for it, but that also means that TanStack Form doesn't keep track of your state. It's best to keep the error state external to the form in this case, just like you can with tanstack query