I have a MessageInput component which triggers a socket connection to the backend when it mounts, and should disconnect from that socket manually on dismount. I am not sure what happened, but at some point yesterday useEffect simply stopped running cleanup.
When I close the app I see the accumulated disconnections all at once.
User disconnected...
User disconnected...
User disconnected...
Is there something I am missing in useEffect?
Here is my code:
useEffect(async () => {
const accessToken = await SecureStore.getItemAsync("access-token");
const socket = socketClient(`${process.env.REACT_APP_backend_url}/`, {
auth: {
authToken: accessToken,
},
});
socket.emit("message", message);
return () => socket.disconnect();
}, []);
CodePudding user response:
async
functions return promises, so you're not actually returning a cleanup function. React ignores the promise that you return to it.
You'll need to do something like this:
useEffect(() => {
let socket;
(async () => {
const accessToken = await SecureStore.getItemAsync("access-token");
socket = socketClient(`${process.env.REACT_APP_backend_url}/`, {
auth: {
authToken: accessToken,
},
});
socket.emit("message", message);
})()
return () => {
if (socket) {
socket.disconnect();
}
}
}, []);