Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Argument of type '() => () => Promise<void>' is not assignable to parameter of type 'EffectCallback'

My code is:

    useEffect(() => {
        document.querySelector('body').style['background-color'] = 'rgba(173, 232, 244,0.2)';
        window.$crisp.push(['do', 'chat:hide']);

        return async () => {
            window.$crisp.push(['do', 'chat:show']);
            document.querySelector('body').style['background-color'] = '#ffffff';
            if (router.query.id) {
                const resDoc = await firebase.firestore().doc(`documents/${router.query.id}`).get();
                if (resDoc.exists) {
                    await clearDocPrediction(router.query.id);
                }
            }
        };
    }, []);

Now the reason I'm returning is because I believe that it performs function cleanup on unload, so I need to keep that. This is some sort of build error that I'm not quite sure how to resolve. Any help would be greatly appreciated.

like image 829
Shamoon Avatar asked Mar 02 '23 14:03

Shamoon


2 Answers

Effect's callback function should return void, e.g.:

useEffect(() => { // callback; it returns void
  console.log("Hi")
}, [])

Or

It should return a "cleanup" function of type () => void, e.g.:

useEffect(() => {
  console.log("Hi")
  return () => { // cleanup function of type : () => void
    console.log("Cleanup")
  }
}, [])

You are getting the error because the cleanup function in your code is not of type () => void, but of type () => Promise<void>, e.g.:

Argument of type '() => () => Promise' is not assignable to parameter of type 'EffectCallback'. Type '() => Promise' is not assignable to type 'void | Destructor'.

useEffect(() => {
  console.log("Hi")
  return async () => { // WRONG
    console.log("Cleanup")
  }
}, [])

Hence, here is how you can refactor your "cleanup" function to fix it:

return () => { // Remove async from here
  const clear = async () => { // Create a new async function: clear
    // write your cleanup code here
  };
  clear() // Call the clear() function
};
like image 119
Ajeet Shah Avatar answered Apr 30 '23 00:04

Ajeet Shah


The useEffect callback should have return type void. So you can't return a Promise:

useEffect(() => {
        document.querySelector('body').style['background-color'] = 'rgba(173, 232, 244,0.2)';
        window.$crisp.push(['do', 'chat:hide']);

        window.$crisp.push(['do', 'chat:show']);
        document.querySelector('body').style['background-color'] = '#ffffff';
        if (router.query.id) {
            firebase.firestore()
                .doc(`documents/${router.query.id}`)
                .get()
                .then((resDoc) => {
                    if (resDoc.exists) {
                        clearDocPrediction(router.query.id);
                    }
                });
        }
}, []);
like image 37
MrCodingB Avatar answered Apr 30 '23 02:04

MrCodingB