Skip to content

Instantly share code, notes, and snippets.

@MarekZeman91
Created April 18, 2022 00:02
Show Gist options
  • Save MarekZeman91/1f369717779a74cbf67109bbeb06efcf to your computer and use it in GitHub Desktop.
Save MarekZeman91/1f369717779a74cbf67109bbeb06efcf to your computer and use it in GitHub Desktop.
import { DependencyList, useEffect } from 'react';
export type AsyncDestructor = () => void;
export type SetDestructor = (setDestructor: AsyncDestructor) => void;
export type EffectAsyncCallback = (destructor: SetDestructor) => Promise<void>;
export const useEffectAsync = (asyncEffect: EffectAsyncCallback, deps: DependencyList) => {
useEffect(() => {
let destructor: AsyncDestructor = () => {};
asyncEffect(newDestructor => (destructor = newDestructor));
return destructor;
}, deps);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment