I've been struggling with managing our single page application's history through the History-API.
Even though I've been able to find a working solution for my problem, there's still one thing I'm having trouble wrapping my head around.
I've simplified my code to the following:
window.onpopstate = e => console.log("Popped:", e.state.index, ", ", window.history.state.index);
for (let i = 0; i < 10; i++) {
window.history.pushState({index: i.toString()}, "");
}
// This correctly logs "9"
console.log("Expected 9: " + window.history.state.index);
window.history.go(-4);
// I would expect this to log "5", but it logs "9"
console.log("Expected 5: " + window.history.state.index);
// This will log either "5" or "9", depending on the set ms
setTimeout(() => console.log("Expected 5: " + window.history.state.index), 100);
As described in the comments, the window.history.state
does not reflect the expected value after calling window.history.go()
.
I was under the assumption that window.history.go()
would continue upon completion and I haven't found anything about whether this is true.
Strangely, the described behaviour only seems to occur if pushing multiple states and/or traversing multiple history steps, which adds to my confusion.
Maybe somebody with a deeper knowledge of how the states are managed internally could explain it and/or point me in the right direction.
Juan Pablo Isaza