Exit when the page is refreshed 🙁 help
Code:
useEffect(() => {
const handleBeforeUnload = async (event) => {
try {
const cookies = new Cookies();
cookies.remove("_token");
const response = await axios.get("http://localhost:3001/logout", {
withCredentials: true,
});
} catch (error) {
console.error("Hata:", error);
}
};
window.addEventListener("beforeunload", handleBeforeUnload);
return () => {
window.removeEventListener("beforeunload", handleBeforeUnload);
};
}, []);
Only exit when the tab is closed
2
Answers
Try VisibilityChange event listener
https://developer.mozilla.org/en-US/docs/Web/API/Document/visibilitychange_event
beforeunload
will call in both cases ( In tab close event and a page refresh event). but, you can usevisibilitychange
event here. You can add condition like this.Logic for check page is refreshed or not
Full code:
I have done this way in past, I don’t know this is the best way or not. Let me know, if you have any doubts.