diff --git a/src/index.js b/src/index.js index 8cfb52e..2799747 100644 --- a/src/index.js +++ b/src/index.js @@ -37,6 +37,7 @@ function locationToString(location) { } function syncReduxAndRouter(history, store, selectRouterState = SELECT_STATE) { + let lastRoute; const getRouterState = () => selectRouterState(store.getState()); if(!getRouterState()) { @@ -47,22 +48,26 @@ function syncReduxAndRouter(history, store, selectRouterState = SELECT_STATE) { } const unsubscribeHistory = history.listen(location => { + const newLocation = locationToString(location); // Avoid dispatching an action if the store is already up-to-date, // even if `history` wouldn't do anything if the location is the same - if(getRouterState().path !== locationToString(location)) { - store.dispatch(updatePath(locationToString(location))); + if(getRouterState().path !== newLocation) { + lastRoute = newLocation; + store.dispatch(updatePath(newLocation)); } }); const unsubscribeStore = store.subscribe(() => { const routing = getRouterState(); - // Don't update the router if nothing has changed. The - // `noRouterUpdate` flag can be set to avoid updating altogether, + // Don't update the router if the routing state hasn't changed or the new routing path + // is already the current location. + // The `noRouterUpdate` flag can be set to avoid updating altogether, // which is useful for things like loading snapshots or very special // edge cases. - if(routing.path !== locationToString(window.location) && + if(lastRoute !== routing.path && routing.path !== locationToString(window.location) && !routing.noRouterUpdate) { + lastRoute = routing.path; history.pushState(null, routing.path); } }); @@ -77,5 +82,5 @@ module.exports = { UPDATE_PATH, updatePath, syncReduxAndRouter, - routeReducer: update, + routeReducer: update };