I am trying to alert the user of unsaved changes when they use the back button in the browser and it works when the user hits cancel on the confirm modal but when they click ok to confirm they want to go back the page does not go back.
These are my funcitons for handling back:
const handleBrowserBackBtn = () => {
handleBackClick();
window.history.pushState(null, document.title, window.location.href);
}
useLayoutEffect(() => {
window.history.pushState(null, document.title, window.location.href);
window.addEventListener("popstate", handleBrowserBackBtn);
return () => {
window.removeEventListener("popstate", handleBrowserBackBtn);
};
});
const handleBackClick = () => {
if(addingNew || editing){
if(confirm("You have unsaved changes. Are you sure you want to go back?")){
window.location.back()
};
}
}
I am trying to send the user back to the home screen. But I get this endless loop of confirm pop up.
try to use this for your app :