Skip to content

Instantly share code, notes, and snippets.

@codephi
Created December 6, 2019 06:51
Show Gist options
  • Save codephi/d9b5199e839f6b91fca617921329d888 to your computer and use it in GitHub Desktop.
Save codephi/d9b5199e839f6b91fca617921329d888 to your computer and use it in GitHub Desktop.
usePromise is a React hook. It ensures that you will not experience memory leak after unmont component. See it working at: https://codesandbox.io/embed/youthful-wilbur-eu9bb?expanddevtools=1&fontsize=14&hidenavigation=1&theme=dark
import { useCallback, useRef, useEffect } from 'react'
export function usePromise (promiseFn) {
const mountedRef = useRef(false)
const isMounted = useCallback(() => mountedRef.current, [])
useEffect(() => {
mountedRef.current = true
return () => {
mountedRef.current = false
}
})
return useCallback((...args) =>
new Promise((resolve, reject) => {
const onValue = value => {
isMounted() && resolve(value)
}
const onError = error => {
isMounted() && reject(error)
}
const promise = (typeof promiseFn === 'function')
? promiseFn.apply(this, args)
: promiseFn
promise.then(onValue, onError)
}),
[]
)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment