I have this use case: One page with two subpages under a hashrouter
for example
domain.com/post/1
domain.com/post/1#details
in the #details hash route I want to listen to "back button clicks" and do one api call to update the post before page closes.
During this time want to show a spinner, then after api call is done let browser finish the window.history.back (back button logic)
Is that possible, and how ?
I am trying this now with partial success.
I am using React framework with NextJS and have following code inside one component
useEffect(() => {
async function onPopState(e: PopStateEvent): Promise<void> {
return new Promise((resolve) => handleWantToClose(resolve));
}
window.addEventListener('popstate', onPopState);
return () => {
window.removeEventListener('popstate', onPopState);
};
});
In the above snippet handleWantToClose is called fine when clicking back navigate browser button (or mobile back button ios/android)
Thing is that I cannot delay the pop state. It does not wait for the promise to finish resolve.
handleWantToClose funcion is just doing one api call, then calling the resolve function.
Any idea ? This would be extremely useful to provide great user interface for the website to the mobile users especially that use back button a lot to navigate websites.
Other things I tried
e.preventDefault();
e.stopPropagation();
e.stopImmediatePropagation();
on my popstatelistener, then after api call was done, triggered window.history.back() manually but did not work.
The popstate event is not cancellable.