Skip to content

Add useAsync hook to leverage new Hooks proposal #9

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

Merged
merged 22 commits into from
Dec 30, 2018
Merged
Show file tree
Hide file tree
Changes from 5 commits
Commits
Show all changes
22 commits
Select commit Hold shift + click to select a range
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
30 changes: 26 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -31,13 +31,13 @@
</a>
</p>

React component for declarative promise resolution and data fetching. Leverages the Render Props pattern for ultimate
flexibility as well as the new Context API for ease of use. Makes it easy to handle loading and error states, without
assumptions about the shape of your data or the type of request.
React component for declarative promise resolution and data fetching. Leverages the Render Props pattern and Hooks for
ultimate flexibility as well as the new Context API for ease of use. Makes it easy to handle loading and error states,
without assumptions about the shape of your data or the type of request.

- Zero dependencies
- Works with any (native) promise
- Choose between Render Props and Context-based helper components
- Choose between Render Props, Context-based helper components or the `useAsync` hook
- Provides convenient `isLoading`, `startedAt` and `finishedAt` metadata
- Provides `cancel` and `reload` actions
- Automatic re-run using `watch` prop
Expand Down Expand Up @@ -71,6 +71,28 @@ npm install --save react-async

## Usage

As a hook with `useAsync`:

```js
import { useAsync } from "react-async"

const loadJson = () => fetch("/some/url").then(res => res.json())

const MyComponent = () => {
const { data, error, isLoading } = useAsync({ promiseFn: loadJson })
if (isLoading) return "Loading..."

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can we avoid isLoading, and use React Suspense instead?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suspense is not released yet. Eventually React Async will support both. At first, React Async will maintain its API but use Suspense underneath. Later on I'll look into better integration with the Suspense components (e.g. Placeholder/Timeout). Right now there's no telling how Suspense will be used in practice.

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I have to agree with @sibelius. It seems like any new api surface for async right now should at least consider the usage of resources, cache invalidation and suspense. The react team has mentioned that react-cache is a WIP and that invalidation is outstanding. Their vision seems to be using resource for data fetching. Any new api surface surface should at least be able to show how it fits into that future.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I agree, I want React Async to be future compatible. I'm confident it will still be relevant despite Suspense offering very similar features. Personally I'm surprised that they even took the whole thing as far as providing a cache mechanism. That to me sound like a very application specific thing. A simple library around Promises could easily provide the same functionality, which is why React Async doesn't do any caching, you can simply bring your own.

So what would closer integration with Suspense look like? I'm hesitant to adopt the same API, and relying on interop between the two (i.e. using Async with Timeout or Placeholder) seems awkward and error prone. What are your thoughts on this?

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Personally I'm surprised that they even took the whole thing as far as providing a cache mechanism.

I haven't dug into code that does the suspending in React reconciler, but the mechanism how WIP react-cache package gets render to suspend is through throwing a pending promise -https://github.com/facebook/react/blob/master/packages/react-cache/src/ReactCache.js#L158 Before throwing the pending promise out to React renderer, one needs to store the promise somewhere, to access it again when promise gets resolved and render is retried, hence the need for react-cache. Also I think the react-cache won't be mandatory for suspense, so anyone can roll their own:

It also serves as a reference for more advanced caching implementations.
https://github.com/facebook/react/tree/master/packages/react-cache

Atleast that's how I understand it.

if (error) return `Something went wrong: ${error.message}`
if (data)
return (
<div>
<strong>Loaded some data:</strong>
<pre>{JSON.stringify(data, null, 2)}</pre>
</div>
)
return null
}
```

Using render props for ultimate flexibility:

```js
Expand Down
5 changes: 3 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@
"src"
],
"scripts": {
"build": "babel src -d lib",
"build": "rimraf lib && babel src -d lib --ignore '**/*spec.js'",
"test": "jest src",
"test:watch": "npm run test -- --watch",
"test:compat": "npm run test:backwards && npm run test:forwards && npm run test:latest",
Expand All @@ -47,7 +47,8 @@
"jest-dom": "2.1.0",
"react": "16.7.0-alpha.0",
"react-dom": "16.7.0-alpha.0",
"react-testing-library": "5.2.3"
"react-testing-library": "5.2.3",
"rimraf": "2.6.2"
},
"jest": {
"coverageDirectory": "./coverage/",
Expand Down
1 change: 1 addition & 0 deletions src/index.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import React from "react"
export { default as useAsync } from "./useAsync"

const isFunction = arg => typeof arg === "function"

Expand Down
13 changes: 10 additions & 3 deletions src/spec.js
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
import "jest-dom/extend-expect"
import React from "react"
import { render, fireEvent, cleanup, waitForElement } from "react-testing-library"
import Async, { createInstance } from "./"
import Async, { createInstance, useAsync } from "./"

afterEach(cleanup)

const resolveIn = ms => value => new Promise(resolve => setTimeout(() => resolve(value), ms))
const resolveIn = ms => value => new Promise(resolve => setTimeout(resolve, ms, value))
const resolveTo = resolveIn(0)
const rejectIn = ms => err => new Promise((resolve, reject) => setTimeout(() => reject(err), ms))
const rejectIn = ms => err => new Promise((resolve, reject) => setTimeout(reject, ms, err))
const rejectTo = rejectIn(0)

test("runs promiseFn on mount", () => {
Expand Down Expand Up @@ -423,3 +423,10 @@ test("an unrelated change in props does not update the Context", async () => {
)
expect(one).toBe(two)
})

test("useAsync returns render props", async () => {
const promiseFn = () => new Promise(resolve => setTimeout(resolve, 0, "done"))
const Async = ({ children, ...props }) => children(useAsync(props))
const { getByText } = render(<Async promiseFn={promiseFn}>{({ data }) => data || null}</Async>)
await waitForElement(() => getByText("done"))
})
96 changes: 96 additions & 0 deletions src/useAsync.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
import { useState, useEffect, useMemo } from "react"

const useAsync = props => {
let counter = 0
let isMounted = false
let lastArgs = undefined

const initialError = props.initialValue instanceof Error ? props.initialValue : undefined
const initialData = initialError ? undefined : props.initialValue
const [data, setData] = useState(initialData)
const [error, setError] = useState(initialError)
const [startedAt, setStartedAt] = useState(props.promiseFn ? new Date() : undefined)
const [finishedAt, setFinishedAt] = useState(props.initialValue ? new Date() : undefined)

const cancel = () => {
counter++
setStartedAt(undefined)
}

const start = () => {
counter++
setStartedAt(new Date())
setFinishedAt(undefined)
}

const end = () => setFinishedAt(new Date())

const handleData = (data, callback = () => {}) => {
if (isMounted) {
end()
setData(data)
setError(undefined)
callback(data)
}
return data
}

const handleError = (error, callback = () => {}) => {
if (isMounted) {
end()
setError(error)
callback(error)
}
return error
}

const onResolve = count => data => count === counter && handleData(data, props.onResolve)
const onReject = count => error => count === counter && handleError(error, props.onReject)

const load = () => {
if (props.promiseFn) {
start()
props.promiseFn(props).then(onResolve(counter), onReject(counter))
}
}

const run = (...args) => {
if (props.deferFn) {
lastArgs = args
start()
return props.deferFn(...args, props).then(onResolve(counter), onReject(counter))
}
}

const reload = () => (lastArgs ? run(...lastArgs) : load())

useEffect(() => {
isMounted = true
return () => (isMounted = false)
}, [])

useEffect(load, [props.promiseFn, props.watch])

return useMemo(
() => ({
isLoading: startedAt && (!finishedAt || finishedAt < startedAt),
startedAt,
finishedAt,
data,
error,
cancel,
run,
reload,
setData: handleData,
setError: handleError,
initialValue: props.initialValue
}),
[data, error, startedAt, finishedAt]
)
}

const unsupported = () => {
throw new Error("useAsync requires [email protected] or later")
}

export default (useState ? useAsync : unsupported)