Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import { useEffect } from 'react'
- interface UseAsyncEffect {
- (
- effect: (isMounted: () => boolean) => unknown | Promise<unknown>,
- inputs?: any[]
- ): void
- <V>(
- effect: (isMounted: () => boolean) => V | Promise<V>,
- destroy?: (result?: V) => void,
- inputs?: any[]
- ): void
- }
- export const useAsyncEffect: UseAsyncEffect = (effect, destroy, inputs) => {
- useEffect(
- () => {
- let result
- let mounted = true
- let maybePromise = effect(() => mounted)
- Promise.resolve(maybePromise).then(value => (result = value))
- return () => {
- mounted = false
- if (typeof destroy === 'function') destroy(result)
- }
- },
- // eslint-disable-next-line react-hooks/exhaustive-deps
- typeof destroy === 'function' ? inputs : destroy
- )
- }
- export default useAsyncEffect
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement