In case anyone facing this issue in React-JS,
let's say you have a useEffect() and want to log the popState on every re-render or (Go-Forward/Go-Back)
useEffect(() => {
function handlePopStateEvent(e) {
console.log(e);
console.log("Check if the function Working")
}
console.log("Check if Effect Working")
window.addEventListener("popstate", handlePopStateEvent);
return () => window.removeEventListener("popstate", handlePopStateEvent);
}, []);
You will need to add some history manually using the history.pushState(), even if you did it by hand let's say you typed in the URL some routes/paths like
http://localhost:5173/lab
http://localhost:5173/home
http://localhost:5173/blog
http://localhost:5173/about
it will not work, the popState() event will not log anything, and if you try to invoke the function manually to see the log you will get undefined.
The solution: in the Console add some history like this:
history.pushState({}, '', '/home');
history.pushState({}, '', '/blog');
history.pushState({}, '', '/about');
history.pushState({}, '', '/lab');
Then when you use the Back/Forward arrows in the browser or Alt + (← →) the popState() will log in to the console like this
On every Back/Forward.
For more understanding of this behavior, you can check the MDN on the History API, popState, and history.push()
Here's the Mdn description:
The popstate event of the Window interface is fired when the active
history entry changes while the user navigates the session history. It
changes the current history entry to that of the last page the user
visited or, if history.pushState() has been used to add a history
entry to the history stack, that history entry is used instead.
Link: https://developer.mozilla.org/en-US/docs/Web/API/Window/popstate_event
popstate
event at codeguage.com/courses/js/events-popstate-event. – Sorehead