I needed to interact with the browser's History object, but it was too mind-bending. So I made this abstraction and then I was able to get my job done.
These functions update and return state using a single property on the real state object, minimizing your odds of bashing history state set by some other part of your app when you use this API.
const historyState = require('better-history-api')
Updates the existing state for the current history item.
The new state object you pass in is merged with the existing state with Object.assign
.
Returns the state object for the current history item.
This adds a callback/middlewarey function that will be called before pushState
is called, no matter who is calling pushState
.
Your function will be passed the current (pre-pushState
) state, and will give you a chance to change it before the history stack changes.
historyState.addBeforePushStateMiddleware(
state => Object.assign(state, { position: currentScrollPosition() })
)
The historyState
object is an event emitter that emits these events:
Emitted immediately after pushState
is called, while the state object is fresh and shiny.
Emitted whenever a popstate
event happens with any associated state. Emits the state object.