From c6ba457dc30123bfe926f5ffcbfb640edaddf097 Mon Sep 17 00:00:00 2001 From: Mikhail Potomin Date: Wed, 3 Jul 2019 13:09:22 +0200 Subject: [PATCH 1/2] Handling fetch error for Mutate --- src/Context.tsx | 2 +- src/Mutate.tsx | 22 +++++++++++++++++++++- 2 files changed, 22 insertions(+), 2 deletions(-) diff --git a/src/Context.tsx b/src/Context.tsx index 05b49218..90d60d59 100644 --- a/src/Context.tsx +++ b/src/Context.tsx @@ -26,7 +26,7 @@ export interface RestfulReactProviderProps { * Depending of your case, it can be easier to add a `localErrorOnly` on your `Mutate` component * to deal with your retry locally instead of in the provider scope. */ - onError?: (err: any, retry: () => Promise, response: Response) => void; + onError?: (err: any, retry: () => Promise, response?: Response) => void; } export const Context = React.createContext>({ diff --git a/src/Mutate.tsx b/src/Mutate.tsx index 4f28f956..1fd618da 100644 --- a/src/Mutate.tsx +++ b/src/Mutate.tsx @@ -162,7 +162,27 @@ class ContextlessMutate extends React }, } as RequestInit); // Type assertion for version of TypeScript that can't yet discriminate. - const response = await fetch(request, { signal: this.signal }); + let response: Response; + try { + response = await fetch(request, { signal: this.signal }); + } catch (e) { + const error = { + message: "Failed to fetch" + e.message ? `: ${e.message}` : "", + data: "", + }; + + this.setState({ + error, + loading: false, + }); + + if (!this.props.localErrorOnly && this.props.onError) { + this.props.onError(error, () => this.mutate(body, mutateRequestOptions)); + } + + throw error; + } + const { data, responseError } = await processResponse(response); // avoid state updates when component has been unmounted From 75426f28251f1662df67ce4d1c52d5e0b8ae26c9 Mon Sep 17 00:00:00 2001 From: Mikhail Potomin Date: Wed, 3 Jul 2019 13:12:26 +0200 Subject: [PATCH 2/2] Handling fetch error for useMutate as well --- src/useMutate.tsx | 22 +++++++++++++++++++++- 1 file changed, 21 insertions(+), 1 deletion(-) diff --git a/src/useMutate.tsx b/src/useMutate.tsx index cbeee327..1de8c8c9 100644 --- a/src/useMutate.tsx +++ b/src/useMutate.tsx @@ -92,7 +92,27 @@ export function useMutate< merge({}, contextRequestOptions, options, propsRequestOptions, mutateRequestOptions, { signal }), ); - const response = await fetch(request); + let response: Response; + try { + response = await fetch(request); + } catch (e) { + const error = { + message: "Failed to fetch" + e.message ? `: ${e.message}` : "", + data: "", + }; + + setState({ + error, + loading: false, + }); + + if (!props.localErrorOnly && context.onError) { + context.onError(error, () => mutate(body, mutateRequestOptions)); + } + + throw error; + } + const { data: rawData, responseError } = await processResponse(response); let data: TData | any; // `any` -> data in error case