Skip to content
This repository has been archived by the owner on Nov 11, 2023. It is now read-only.

fix/132 handle fetch error mutate #134

Merged
merged 2 commits into from
Jul 3, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion src/Context.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ export interface RestfulReactProviderProps<T = any> {
* 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<T | null>, response: Response) => void;
onError?: (err: any, retry: () => Promise<T | null>, response?: Response) => void;
}

export const Context = React.createContext<Required<RestfulReactProviderProps>>({
Expand Down
22 changes: 21 additions & 1 deletion src/Mutate.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -162,7 +162,27 @@ class ContextlessMutate<TData, TError, TQueryParams, TRequestBody> 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
Expand Down
22 changes: 21 additions & 1 deletion src/useMutate.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down