react-async-hook
react-async-hook copied to clipboard
Support for async cleanup functions?
I read #6 and then #7. I saw that handling streams / observables doesn't make sense here, there are other hooks.
My situation is a little different. I'm using nostr, where I create a subscription over a websocket, and then I need to unsubscribe when my component is unmounted. Is there any support for running an async cleanup function in react-async-hook?
Here's an example of what I imagine:
const fetchAndReturnCleanupFunction = async () => {
const unsubscribeFunction = await doSomeSubscribe();
return unusbscribeFunction
}
Where I want unsubscribeFunction
to be called once my component is unmounted. I don't think that's currently possible with useAsync()
right?
I have tried this already a few times in my own code, and I think I was able to abstract it out like so:
export const useAsyncWithCleanup = (
asyncFunction: () => Promise<() => void>,
useEffectDependencies: any[] = []
) => {
const dependencies = [asyncFunction, ...useEffectDependencies];
useEffect(() => {
const asyncFunctionPromise = asyncFunction();
const cleanup = () => {
asyncFunctionPromise.then((cleanupFunction) => {
cleanupFunction();
});
};
return cleanup;
// eslint-disable-next-line react-hooks/exhaustive-deps
}, dependencies);
};
I'm sharing it here as maybe this better explains what I mean. Plus, if you don't think this is a good fit for this package, maybe somebody else will find this in the future following the same path I did. :-)
const SomethingContainer () => {
const [conditionUnmount, setUnmount] = useState(false);
useEffect(()=>{
return ()=>{
if(conditionUnmount){
//clean up here
}
}
})
return <>
{!unmount && <YourFetcherComponent>}
</>
}