Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support for async cleanup functions? #98

Open
chmac opened this issue Jan 17, 2023 · 2 comments
Open

Support for async cleanup functions? #98

chmac opened this issue Jan 17, 2023 · 2 comments

Comments

@chmac
Copy link

chmac commented Jan 17, 2023

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
Copy link
Author

chmac commented Jan 17, 2023

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

@pig800509
Copy link

pig800509 commented Jun 6, 2023

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

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

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants