Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Error on response.ok false #166

Closed
wants to merge 13 commits into from
40 changes: 20 additions & 20 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,12 +1,24 @@
{
"name": "use-http",
"version": "0.2.1",
"version": "0.2.5",
"homepage": "http://use-http.com",
"main": "dist/index.js",
"license": "MIT",
"repository": {
"type": "git",
"url": "https://github.com/alex-cory/use-http.git"
"scripts": {
"prepublishOnly": "yarn build # runs before publish",
"build": "rm -rf dist && tsc --module CommonJS",
"build:watch": "rm -rf dist && tsc -w --module CommonJS",
"tsc": "tsc -p . --noEmit && tsc -p ./src/__tests__",
"test:browser": "yarn tsc && jest -c ./config/jest.config.js --env=jsdom",
"test:browser:watch": "yarn tsc && jest --watch -c ./config/jest.config.js --env=jsdom",
"test:server": "yarn tsc && jest -c ./config/jest.config.js --env=node --testPathIgnorePatterns useFetch.test.tsx makeRouteAndOptions.test.tsx",
"test:server:watch": "yarn tsc && jest --watch -c ./config/jest.config.js --env=node --testPathIgnorePatterns useFetch.test.tsx makeRouteAndOptions.test.tsx",
"test:watch": "yarn test:browser:watch && yarn test:server:watch",
"test": "yarn test:browser && yarn test:server",
"clean": "npm prune; yarn cache clean; rm -rf ./node_modules package-lock.json yarn.lock; yarn",
"lint": "eslint ./src/**/*.{ts,tsx}",
"lint:fix": "npm run lint -- --fix",
"lint:watch": "watch 'yarn lint'"
},
"dependencies": {
"use-ssr": "^1.0.22"
Expand Down Expand Up @@ -47,25 +59,13 @@
"typescript": "^3.4.5",
"watch": "^1.0.2"
},
"scripts": {
"prepublishOnly": "yarn build # runs before publish",
"build": "rm -rf dist && tsc --module CommonJS",
"build:watch": "rm -rf dist && tsc -w --module CommonJS",
"tsc": "tsc -p . --noEmit && tsc -p ./src/__tests__",
"test:browser": "yarn tsc && jest -c ./config/jest.config.js --env=jsdom",
"test:browser:watch": "yarn tsc && jest --watch -c ./config/jest.config.js --env=jsdom",
"test:server": "yarn tsc && jest -c ./config/jest.config.js --env=node --testPathIgnorePatterns useFetch.test.tsx makeRouteAndOptions.test.tsx",
"test:server:watch": "yarn tsc && jest --watch -c ./config/jest.config.js --env=node --testPathIgnorePatterns useFetch.test.tsx makeRouteAndOptions.test.tsx",
"test:watch": "yarn test:browser:watch && yarn test:server:watch",
"test": "yarn test:browser && yarn test:server",
"clean": "npm prune; yarn cache clean; rm -rf ./node_modules package-lock.json yarn.lock; yarn",
"lint": "eslint ./src/**/*.{ts,tsx}",
"lint:fix": "npm run lint -- --fix",
"lint:watch": "watch 'yarn lint'"
},
"files": [
"dist"
],
"repository": {
"type": "git",
"url": "https://github.com/alex-cory/use-http.git"
},
"keywords": [
"react hook",
"react-hook",
Expand Down
14 changes: 14 additions & 0 deletions src/__tests__/useFetch.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -566,6 +566,7 @@ describe('useFetch - BROWSER - errors', (): void => {
fetch.mockRejectOnce(expectedError)
fetch.mockResponseOnce(JSON.stringify(expectedSuccess))
})
console.log('fetch', fetch)

it('should reset the error after each call', async (): Promise<void> => {
const { result } = renderHook(
Expand Down Expand Up @@ -627,4 +628,17 @@ describe('useFetch - BROWSER - errors', (): void => {
expect(result.current.response.ok).toBe(undefined)
expect(result.current.error).toEqual(expectedError)
})

it ('should set the `error` properly when the response.ok is false', async (): Promise<void> => {
fetch.mockResponseOnce('', )
// console.log('fetch.Response', fetch.Response)
const { result } = renderHook(
() => useFetch('https://example.com'),
)
// await waitForNextUpdate()
await result.current.get()
console.log('result', result.current)
expect(result.current.response.ok).toBe(false)
expect(result.current.error).toEqual(expectedError)
})
})
18 changes: 15 additions & 3 deletions src/useFetch.ts
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,7 @@ function useFetch<TData = any>(...args: UseFetchArgs): UseFetch<TData> {

let newData
let theRes
let theErr

try {
theRes = ((await fetch(`${url}${path}${route}`, options)) || {}) as Res<TData>
Expand All @@ -89,7 +90,9 @@ function useFetch<TData = any>(...args: UseFetchArgs): UseFetch<TData> {
try {
newData = await theRes.json()
} catch (err) {
newData = (await theRes.text()) as any // FIXME: should not be `any` type
try {
newData = (await theRes.text()) as any // FIXME: should not be `any` type
} catch(er) {}
}

newData = (defaults.data && isEmpty(newData)) ? defaults.data : newData
Expand All @@ -101,10 +104,19 @@ function useFetch<TData = any>(...args: UseFetchArgs): UseFetch<TData> {

} catch (err) {
if (attempts.current > 0) return doFetch(routeOrBody, body)
if (attempts.current < 1 && timedout.current) setError({ name: 'AbortError', message: 'Timeout Error' })
if (err.name !== 'AbortError') setError(err)
if (attempts.current < 1 && timedout.current) {
setError({ name: 'AbortError', message: 'Timeout Error' })
theErr = err
}
if (err.name !== 'AbortError') {
setError(err)
theErr = err
}

} finally {
console.log('theRes', theRes)
console.log('theErr', theErr)
if (theRes && !theRes.ok && !theErr) setError({ name: theRes.status, message: theRes.statusText })
if (attempts.current > 0) attempts.current -= 1
timedout.current = false
if (timer) clearTimeout(timer)
Expand Down