Skip to content
This repository was archived by the owner on Oct 26, 2018. It is now read-only.

Fix double update on history.pushState #109

Closed
wants to merge 3 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,7 @@ function syncReduxAndRouter(history, store, selectRouterState = SELECT_STATE) {
// history update. It's possible for this to happen when something
// reloads the entire app state such as redux devtools.
let lastRoute = undefined
let historyUpdate = false

if(!getRouterState()) {
throw new Error(
Expand Down Expand Up @@ -132,6 +133,7 @@ function syncReduxAndRouter(history, store, selectRouterState = SELECT_STATE) {
} else if(!locationsAreEqual(getRouterState(), route)) {
// The above check avoids dispatching an action if the store is
// already up-to-date
historyUpdate = true;
const method = location.action === 'REPLACE' ? replacePath : pushPath
store.dispatch(method(route.path, route.state, { avoidRouterUpdate: true }))
}
Expand All @@ -140,6 +142,11 @@ function syncReduxAndRouter(history, store, selectRouterState = SELECT_STATE) {
const unsubscribeStore = store.subscribe(() => {
let routing = getRouterState()

if (historyUpdate) {
historyUpdate = false;
return;
}

// Only trigger history update if this is a new change or the
// location has changed.
if(lastRoute.changeId !== routing.changeId ||
Expand Down
26 changes: 26 additions & 0 deletions test/createTests.js
Original file line number Diff line number Diff line change
Expand Up @@ -515,6 +515,32 @@ module.exports = function createTests(createHistory, name, reset = defaultReset)

storeUnsubscribe()
})

it('only triggers history once when updating path via history push', () => {
const updates = []
const historyUnsubscribe = history.listen(location => {
updates.push(location.pathname);
})

history.pushState(null, '/bar')
history.pushState(null, '/baz')
expect(updates).toEqual(['/', '/bar', '/baz'])

historyUnsubscribe()
})

it('only triggers store once when updating path via history push', () => {
const updates = []
const storeUnsubscribe = store.subscribe(() => {
updates.push(store.getState().routing.path);
})

history.pushState(null, '/bar')
history.pushState(null, '/baz')
expect(updates).toEqual(['/bar', '/baz'])

storeUnsubscribe()
})
})

it('handles basename history option', () => {
Expand Down