Idiomatic approach to error handling when `onSubmit` handler rejects?
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:
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.
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?3 Replies
quickest-silverOP•4w ago
My question is also more relevant for cases where query isn't being used.
passive-yellow•4w ago
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 queryquickest-silverOP•4w ago
ah great - thanks for the detailed answer! In my case, think I'd be dealing with the latter situation 99% of the time, so seems like what I wrote out originally is aligned with that approach