Advertisement
Neko250

useAsyncEffect

May 20th, 2024
588
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
TypeScript 0.85 KB | Source Code | 0 0
  1. import { useEffect } from 'react'
  2.  
  3. interface UseAsyncEffect {
  4.   (
  5.     effect: (isMounted: () => boolean) => unknown | Promise<unknown>,
  6.     inputs?: any[]
  7.   ): void
  8.  
  9.   <V>(
  10.     effect: (isMounted: () => boolean) => V | Promise<V>,
  11.     destroy?: (result?: V) => void,
  12.     inputs?: any[]
  13.   ): void
  14. }
  15.  
  16. export const useAsyncEffect: UseAsyncEffect = (effect, destroy, inputs) => {
  17.   useEffect(
  18.     () => {
  19.       let result
  20.       let mounted = true
  21.       let maybePromise = effect(() => mounted)
  22.  
  23.       Promise.resolve(maybePromise).then(value => (result = value))
  24.  
  25.       return () => {
  26.         mounted = false
  27.         if (typeof destroy === 'function') destroy(result)
  28.       }
  29.     },
  30.  
  31.     // eslint-disable-next-line react-hooks/exhaustive-deps
  32.     typeof destroy === 'function' ? inputs : destroy
  33.   )
  34. }
  35.  
  36. export default useAsyncEffect
  37.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement