react-async-hook icon indicating copy to clipboard operation
react-async-hook copied to clipboard

Support for async cleanup functions?

Open chmac opened this issue 2 years ago • 2 comments

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?

chmac avatar Jan 17 '23 10:01 chmac

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. :-)

chmac avatar Jan 17 '23 10:01 chmac

const SomethingContainer () => {
const [conditionUnmount, setUnmount] = useState(false);

useEffect(()=>{
   return ()=>{
       if(conditionUnmount){
       //clean up here
       }
   }
})

return <>
{!unmount && <YourFetcherComponent>}
</>
}

pig800509 avatar Jun 06 '23 02:06 pig800509