How do i handle a fetcher.load error properly? #10185
-
I have a general question regarding fetchers. I'm using fetcher.load() to load a resource route in my project. This route has some logic that sometimes throws JSON as an error. My question is: how am I supposed to handle this? I use this inside a dialog where I fetch users based on an input field, and I can't seem to find a nice way to catch the error without getting to an error boundary? |
Beta Was this translation helpful? Give feedback.
Answered by
sergiodxa
Nov 2, 2024
Replies: 1 comment 1 reply
-
Catch the error inside the loader and return a response, so your loader never throws, e.g. export async function loader({ request }: LoaderFunctionArgs) {
try {
// do things here
// send a success response
return json({ ok: true as const, ...data })
} catch (error) {
// send a bad request response
return json({ ok: false as const, error: (error as Error).message }, 400);
}
} Then in your component: let { load, data } = useFetcher<typeof loader>()
if (!data) {
return <button type="button" onClick={() => load("/resource/route")}>Load</button>
}
if (!data.ok) {
return <p>Something failed: {data.message}</p>
}
if (data.ok) {
return <p>Success! {data.something}</p>
} |
Beta Was this translation helpful? Give feedback.
1 reply
Answer selected by
ArvidAnderson
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Catch the error inside the loader and return a response, so your loader never throws, e.g.
Then in your component: