Skip to content

Commit e7f85bc

Browse files
authored
feat: Forward the original error (#303)
1 parent dd19f1b commit e7f85bc

File tree

2 files changed

+22
-3
lines changed

2 files changed

+22
-3
lines changed

src/__tests__/useFetch.test.tsx

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1084,6 +1084,23 @@ describe('useFetch - BROWSER - errors', (): void => {
10841084
expect(result.current.data).toEqual([])
10851085
})
10861086

1087+
it('should set the `error` with custom errors', async (): Promise<void> => {
1088+
const customError = { id: 'Custom Error'}
1089+
fetch.resetMocks()
1090+
fetch.mockResponse(() => Promise.reject(customError))
1091+
const { result } = renderHook(
1092+
() => useFetch('https://example.com', {
1093+
data: [],
1094+
cachePolicy: NO_CACHE
1095+
})
1096+
)
1097+
expect(result.current.data).toEqual([])
1098+
expect(result.current.loading).toBe(false)
1099+
await act(result.current.get)
1100+
expect(result.current.error).toEqual(customError)
1101+
expect(result.current.data).toEqual([])
1102+
})
1103+
10871104
it('should reset the error after each call', async (): Promise<void> => {
10881105
fetch.resetMocks()
10891106
fetch.mockRejectOnce(expectedError)

src/useFetch.ts

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -84,7 +84,7 @@ function useFetch<TData = any>(...args: UseFetchArgs): UseFetch<TData> {
8484
body,
8585
interceptors.request
8686
)
87-
87+
8888
error.current = undefined
8989

9090
// don't perform the request if there is no more data to fetch (pagination)
@@ -151,8 +151,10 @@ function useFetch<TData = any>(...args: UseFetchArgs): UseFetch<TData> {
151151
const theData = await retry(opts, routeOrBody, body)
152152
return theData
153153
}
154-
if (err.name !== 'AbortError') error.current = makeError(err.name, err.message)
155-
154+
if (err.name !== 'AbortError') {
155+
error.current = err
156+
}
157+
156158
} finally {
157159
timedout.current = false
158160
if (timer) clearTimeout(timer)

0 commit comments

Comments
 (0)