Skip to content

Commit 4069603

Browse files
committed
Add check response.ok to default useFetch formatter
1 parent fe6a535 commit 4069603

File tree

3 files changed

+26
-2
lines changed

3 files changed

+26
-2
lines changed

package.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
{
22
"name": "react-fetch-hook",
3-
"version": "1.2.1",
3+
"version": "1.2.2",
44
"description": "React fetch hook",
55
"main": "./dist/index.js",
66
"scripts": {

src/__tests__/useFetch.test.js

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -79,4 +79,23 @@ describe("useFetch", () => {
7979
expect(fetch.mock.calls[0][1]).toMatchObject({ ...options });
8080
});
8181
});
82+
83+
it("error on throw error", async () => {
84+
fetch.mockReject(new Error("fake error message"));
85+
86+
const Component = () => {
87+
const result = useFetch("https://google.com");
88+
return (result.error && result.error.message) || "text";
89+
};
90+
91+
const { container, rerender } = render(<Component />);
92+
93+
await wait(() => {
94+
rerender(<Component />);
95+
96+
expect(fetch.mock.calls.length).toEqual(1);
97+
expect(container).toHaveTextContent("fake error message");
98+
expect(fetch.mock.calls[0][0]).toEqual("https://google.com");
99+
});
100+
});
82101
});

src/useFetch.js

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,12 @@ export function useFetch<T>(
1111
path: RequestInfo,
1212
options?: { ...RequestOptions, formatter?: Response => Promise<T> }
1313
): TUseFetchResult<T> {
14-
const defaultFormatter = response => response.json();
14+
const defaultFormatter = response => {
15+
if (!response.ok) {
16+
throw Error(response.statusText);
17+
}
18+
return response.json();
19+
};
1520
const fetchInstance = formatter => (path, options) => {
1621
return fetch(path, options).then((typeof formatter === "function" && formatter) || defaultFormatter);
1722
};

0 commit comments

Comments
 (0)