Allow to persist current history state when replacing state with navigate method
See original GitHub issueHello there General Kyoetic 🖖
Today, we ran into an issue with a self contained component that uses the History api to manage past states. That component pushes a new state with a state object when any of its values change (form type component) and also listens to the popstate
event to then extract the state object and rehydrate the previous values in its React state. This is done to avoid unnecessary round trips to the API when we had already loaded these values previously.
All was fine with this component’s life cycle when browsing through history with the Back and Forward buttons, however that stopped working when another unrelated component on the page started using raviger’s navigate
method with the replace
boolean set to true
.
The reason is that the navigate
method always pushes a null
state object (first parameter of history.replaceState
).
https://github.com/kyeotic/raviger/blob/74e3b87eaf108d0950ab09f368f1f91f23345dcb/src/navigate.js#L25
This causes our component to have lost the state object it had pushed, and thus it fails to rehydrate values properly.
We currently fixed it by replacing the navigate(url, true)
call by this:
// reuse the current history state when replacing state
window.history.replaceState(history.state, null, url);
dispatchEvent(new PopStateEvent('popstate', null));
But ideally we’d like to have a way to do replace state with raviger’s navigate
while still reusing the current history.state
.
Do you think there would be a way to introduce either an option, or a state object parameter to the navigate
method?
Thanks a lot for your help 😃
Issue Analytics
- State:
- Created 3 years ago
- Comments:6 (6 by maintainers)
I personally think that allowing to pass your own state object is more versatile than the option to persist the current state. Also makes it closer to the native API so easy for users to understand. That is my opinion 😃
FYI I just integrated the change and it looks to be working fine! Thanks again 👍