Created
December 26, 2020 10:35
-
-
Save dobernike/ab3d20cf8147530627886385c81e8542 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 { DependencyList, useEffect } from 'react' | |
| type Effect<T> = (isMounted: () => boolean) => T | PromiseLike<T> | |
| type Destroy<T> = DependencyList | ((result: T) => void) | |
| function hasDestroy<T>(destroy?: Destroy<T>): destroy is (result: T) => void { | |
| return typeof destroy === 'function' | |
| } | |
| export function useAsyncEffect<T = unknown>( | |
| effect: Effect<T>, | |
| inputs?: DependencyList, | |
| destroy?: Destroy<T>, | |
| ) { | |
| useEffect(function () { | |
| let result: T | |
| let mounted = true | |
| const maybePromise = effect(() => mounted) | |
| Promise.resolve(maybePromise).then(value => { | |
| result = value | |
| }) | |
| return () => { | |
| mounted = false | |
| if (hasDestroy(destroy)) { | |
| return destroy(result) | |
| } | |
| } | |
| }, inputs) | |
| } | |
| // possible usage | |
| useAsyncEffect(async () => { | |
| if (!changes) setLoaded(false) | |
| const ch = api.changes( | |
| // some changes | |
| ) | |
| setChanges(ch) | |
| setLoaded(true) | |
| }, [api]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment