I’m developing a React application where the user should be logged off when he clicks on the browser back button from the dashboard.
I’m calling window.onpopstate event inside componentDidUpdate() method like below. But the code seems to work only one time. When I click on Browser’s Back button for the first time, it is working fine. And when I login again for the second time and try to click on the Browser back button, this time ComponentDidUpdate() is not even called.
This happens until I clear my browser cache. After clearing browser cache, again, only for the first time ComponentDidUpdate() is called on click of Browser Back button. Please help me with this. This is my first time with window event handlers. What am I doing wrong?
Do I need to write this functionality in any other lifecycle methods? Please suggest.
ComponentDidUpdate(prevState) {
console.log("DID UPDATE CALLED"); // this works only for the first time.
const location = window.location.href;
if(location.includes('dashboard') { // I want this code to work only when the user is in dashboard
window.onpopstate = (e) => {
if (e.state) {
this.onSignOffClick(); // a function to display a popup asking for the user if he wants to logoff
}
};
window.history.pushState({name: "BackButton"}, "back button clicked", location );
window.history.pushState({name: "BackButton"}, "back button clicked", location );
}
}
Basically, I want to display a popup asking for the user if he wants to logoff (i.e., trigger this.onSignOffClick) every time he clicks on the Browser back button.
Someone please help me. I’m struggling for a long time to achieve this.
Any idea or any advise would help.
Thanks in advance!