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 useAsync hook to leverage new Hooks proposal #9

Merged
merged 22 commits into from
Dec 30, 2018
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
Prev Previous commit
Next Next commit
Update useAsync to use useRef for instance variables.
  • Loading branch information
ghengeveld committed Nov 7, 2018
commit d8a82451c2f99759140f79a374f65ad1ae8ae0d1
22 changes: 11 additions & 11 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

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

afterEach(cleanup)

Expand Down Expand Up @@ -423,10 +423,3 @@ 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"))
})
89 changes: 39 additions & 50 deletions src/useAsync.js
Original file line number Diff line number Diff line change
@@ -1,92 +1,81 @@
import { useState, useEffect, useMemo } from "react"
import { useState, useEffect, useMemo, useRef } from "react"

const useAsync = (opts, init) => {
let counter = 0
let isMounted = false
let lastArgs = undefined
const counter = useRef(0)
const isMounted = useRef(true)
const lastArgs = useRef(undefined)

const options = typeof opts === "function" ? { promiseFn: opts, initialValue: init } : opts
const { promiseFn, deferFn, initialValue, onResolve, onReject, watch } = options

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

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

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

const end = () => setFinishedAt(new Date())
const [state, setState] = useState({
data: initialValue instanceof Error ? undefined : initialValue,
error: initialValue instanceof Error ? initialValue : undefined,
startedAt: promiseFn ? new Date() : undefined,
finishedAt: initialValue ? new Date() : undefined,
})

const handleData = (data, callback = () => {}) => {
if (isMounted) {
end()
setData(data)
setError(undefined)
if (isMounted.current) {
setState(state => ({ ...state, data, error: undefined, finishedAt: new Date() }))
callback(data)
}
return data
}

const handleError = (error, callback = () => {}) => {
if (isMounted) {
end()
setError(error)
if (isMounted.current) {
setState(state => ({ ...state, error, finishedAt: new Date() }))
callback(error)
}
return error
}

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

const start = () => {
counter.current++
setState(state => ({
...state,
startedAt: new Date(),
finishedAt: undefined,
}))
}

const load = () => {
if (promiseFn) {
if (promiseFn && !(initialValue && counter.current === 0)) {
start()
promiseFn(options).then(handleResolve(counter), handleReject(counter))
promiseFn(options).then(handleResolve(counter.current), handleReject(counter.current))
}
}

const run = (...args) => {
if (deferFn) {
lastArgs = args
start()
return deferFn(...args, options).then(handleResolve(counter), handleReject(counter))
lastArgs.current = args
return deferFn(...args, options).then(handleResolve(counter.current), handleReject(counter.current))
}
}

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

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

useEffect(load, [promiseFn, watch])
useEffect(() => () => (isMounted.current = false), [])

return useMemo(
() => ({
isLoading: startedAt && (!finishedAt || finishedAt < startedAt),
startedAt,
finishedAt,
data,
error,
...state,
isLoading: state.startedAt && (!state.finishedAt || state.finishedAt < state.startedAt),
initialValue,
cancel,
run,
reload,
reload: () => (lastArgs ? run(...lastArgs) : load()),
cancel: () => {
counter.current++
setState(state => ({ ...state, startedAt: undefined }))
},
setData: handleData,
setError: handleError
setError: handleError,
}),
[data, error, startedAt, finishedAt]
[state]
)
}

Expand Down
Loading