Home > Software engineering >  How to call an async cleanup function?
How to call an async cleanup function?

Time:05-01

How can I call an async cleanup function in useEffect?

useEffect(() => {
    return () => Voice.destroy().then(Voice.removeAllListeners);
  }, []);

The EffectCallback expects void, not Promise<void>

CodePudding user response:

You can wrap the body in curly braces, because currently it returns the Promise (this is what happens when you omit the curly braces, a one line return), which makes your cleanup function return a Promise<void>. With curly braces, it will be just the body of the function and not an implied return statement:

useEffect(() => {
    return () => {
           Voice.destroy().then(Voice.removeAllListeners)
        };
  }, []);


  • Related