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

Add statusCode to useAsync #320

Open
wants to merge 3 commits into
base: next
Choose a base branch
from
Open
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
1 change: 1 addition & 0 deletions .node-version
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
14.16.0
7 changes: 7 additions & 0 deletions docs/api/state.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ These are returned in an object by `useAsync()` or provided by `<Async>` as rend
- [`startedAt`](#startedat) When the current/last promise was started.
- [`finishedAt`](#finishedat) When the last promise was fulfilled or rejected.
- [`status`](#status) One of: `initial`, `pending`, `fulfilled`, `rejected`.
- [`statusCode`](#statusCode) The HTTP response status code (`useAsync` only).
- [`isInitial`](#isinitial) true when no promise has ever started, or one started but was cancelled.
- [`isPending`](#ispending) true when a promise is currently awaiting settlement. Alias: `isLoading`
- [`isFulfilled`](#isfulfilled) true when the last promise was fulfilled. Alias: `isResolved`
Expand Down Expand Up @@ -64,6 +65,12 @@ Tracks when the last promise was resolved or rejected.

One of: `initial`, `pending`, `fulfilled`, `rejected`. These are available for import as `statusTypes`.

## `statusCode`

> `number`

The HTTP response status code (`useAsync` only).

## `isInitial`

> `boolean`
Expand Down
1 change: 1 addition & 0 deletions packages/react-async/src/propTypes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ const stateObject =
startedAt: PropTypes.instanceOf(Date),
finishedAt: PropTypes.instanceOf(Date),
status: PropTypes.oneOf(["initial", "pending", "fulfilled", "rejected"]),
statusCode: PropTypes.number,
isInitial: PropTypes.bool,
isPending: PropTypes.bool,
isLoading: PropTypes.bool,
Expand Down
2 changes: 2 additions & 0 deletions packages/react-async/src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -108,6 +108,7 @@ export type AsyncFulfilled<T, S = AbstractState<T>> = S & {
startedAt: Date
finishedAt: Date
status: "fulfilled"
statusCode: number
isInitial: false
isPending: false
isLoading: false
Expand All @@ -123,6 +124,7 @@ export type AsyncRejected<T, S = AbstractState<T>> = S & {
startedAt: Date
finishedAt: Date
status: "rejected"
statusCode: number
isInitial: false
isPending: false
isLoading: false
Expand Down
20 changes: 20 additions & 0 deletions packages/react-async/src/useAsync.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -266,4 +266,24 @@ describe("useFetch", () => {
expect(err.message).toEqual("400 Bad Request")
expect(err.response).toBe(errorResponse)
})

test("statusCode parsing", async () => {
const response = { ok: true, status: 205, body: "", json }
globalScope.fetch.mockResolvedValue(response)
let lastStatus, lastStatusCode
const component = (
<Fetch input="/test">
{({ statusCode, status }) => {
lastStatus = status
lastStatusCode = statusCode

return <div />
}}
</Fetch>
)
render(component)
await sleep(10)
expect(lastStatus).toEqual("fulfilled")
expect(lastStatusCode).toEqual(205)
})
})
18 changes: 13 additions & 5 deletions packages/react-async/src/useAsync.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import React, { useCallback, useDebugValue, useEffect, useMemo, useRef, useReducer } from "react"
import React, { useCallback, useDebugValue, useEffect, useMemo, useRef, useReducer, useState } from "react"

import globalScope, { MockAbortController, noop } from "./globalScope"
import {
Expand Down Expand Up @@ -264,6 +264,10 @@ interface FetchRun<T> extends Omit<AbstractState<T>, "run"> {
run(): void
}

type StatusCode<S> = S & {
statusCode?: number
}

type FetchRunArgs =
| [(params?: OverrideParams) => OverrideParams]
| [OverrideParams]
Expand All @@ -280,20 +284,24 @@ function isEvent(e: FetchRunArgs[0]): e is Event | React.SyntheticEvent {
* @param {RequestInfo} resource
* @param {RequestInit} init
* @param {FetchOptions} options
* @returns {AsyncState<T, FetchRun<T>>}
* @returns {AsyncState<T, StatusCode<T>>}
*/
function useAsyncFetch<T>(
resource: RequestInfo,
init: RequestInit,
{ defer, json, ...options }: FetchOptions<T> = {}
): AsyncState<T, FetchRun<T>> {
): AsyncState<T, StatusCode<FetchRun<T>>> {
const [statusCode, setStatusCode] = useState<number|undefined>()
const method = (resource as Request).method || (init && init.method)
const headers: Headers & Record<string, any> =
(resource as Request).headers || (init && init.headers) || {}
const accept: string | undefined =
headers["Accept"] || headers["accept"] || (headers.get && headers.get("accept"))
const doFetch = (input: RequestInfo, init: RequestInit) =>
globalScope.fetch(input, init).then(parseResponse(accept, json))
globalScope.fetch(input, init).then((response) => {
setStatusCode(response.status)
return parseResponse(accept, json)(response)
})
const isDefer =
typeof defer === "boolean" ? defer : ["POST", "PUT", "PATCH", "DELETE"].indexOf(method!) !== -1
const fn = isDefer ? "deferFn" : "promiseFn"
Expand Down Expand Up @@ -327,7 +335,7 @@ function useAsyncFetch<T>(
[fn]: isDefer ? deferFn : promiseFn,
})
useDebugValue(state, ({ counter, status }) => `[${counter}] ${status}`)
return state
return { ...state, statusCode }
}

const unsupported = () => {
Expand Down