Skip to content

Types fix, useAsync hook + removing negation #13

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

Open
wants to merge 6 commits into
base: master
Choose a base branch
from
Open
Changes from 1 commit
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
Prev Previous commit
Next Next commit
feat: useAsync hook for restoring current value
Minimum number of rerenders
  • Loading branch information
mytecor authored Jun 28, 2021
commit 1734a8c39ebe49bf155d5834e08579efedf96f15
23 changes: 22 additions & 1 deletion src/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import {DependencyList, useEffect, useState} from 'react'
import { DependencyList, useRef, useEffect, useState, useReducer, useMemo } from 'react'

export function useAsyncMemo<T>(factory: (...args: any) => Promise<T>, deps?: DependencyList, initial?: T) {
let [val, setVal] = useState(initial)
Expand All @@ -14,3 +14,24 @@ export function useAsyncMemo<T>(factory: (...args: any) => Promise<T>, deps?: De

return val
}

export function useAsync<T>(factory: (...args: any) => Promise<T>, deps?: DependencyList, initial?: T) {
let forceUpdate = useReducer(x => !x, false)[1]
let val = useRef(initial)

useMemo(() => val.current = initial, deps)
useEffect(() => {
let pending = true
factory().then(res => {
if(pending) {
val.current = res
forceUpdate()
}
})
return () => {
pending = false
}
}, deps)

return val.current
}