Reputation: 43599
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.
Upvotes: 12
Views: 19909
Reputation: 19853
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
};
Upvotes: 14
Reputation: 2314
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);
}
});
}
}, []);
Upvotes: 3