Created
December 6, 2019 06:51
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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