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

Commit abe1767

Browse files
committed
Merge pull request #30 from mariocasciaro/fix-loop
Prevent infinite loops when state is updated before the actual history change is fired
2 parents 4097c96 + 1487b74 commit abe1767

File tree

1 file changed

+11
-6
lines changed

1 file changed

+11
-6
lines changed

src/index.js

Lines changed: 11 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,7 @@ function locationToString(location) {
3737
}
3838

3939
function syncReduxAndRouter(history, store, selectRouterState = SELECT_STATE) {
40+
let lastRoute;
4041
const getRouterState = () => selectRouterState(store.getState());
4142

4243
if(!getRouterState()) {
@@ -47,22 +48,26 @@ function syncReduxAndRouter(history, store, selectRouterState = SELECT_STATE) {
4748
}
4849

4950
const unsubscribeHistory = history.listen(location => {
51+
const newLocation = locationToString(location);
5052
// Avoid dispatching an action if the store is already up-to-date,
5153
// even if `history` wouldn't do anything if the location is the same
52-
if(getRouterState().path !== locationToString(location)) {
53-
store.dispatch(updatePath(locationToString(location)));
54+
if(getRouterState().path !== newLocation) {
55+
lastRoute = newLocation;
56+
store.dispatch(updatePath(newLocation));
5457
}
5558
});
5659

5760
const unsubscribeStore = store.subscribe(() => {
5861
const routing = getRouterState();
5962

60-
// Don't update the router if nothing has changed. The
61-
// `noRouterUpdate` flag can be set to avoid updating altogether,
63+
// Don't update the router if the routing state hasn't changed or the new routing path
64+
// is already the current location.
65+
// The `noRouterUpdate` flag can be set to avoid updating altogether,
6266
// which is useful for things like loading snapshots or very special
6367
// edge cases.
64-
if(routing.path !== locationToString(window.location) &&
68+
if(lastRoute !== routing.path && routing.path !== locationToString(window.location) &&
6569
!routing.noRouterUpdate) {
70+
lastRoute = routing.path;
6671
history.pushState(null, routing.path);
6772
}
6873
});
@@ -77,5 +82,5 @@ module.exports = {
7782
UPDATE_PATH,
7883
updatePath,
7984
syncReduxAndRouter,
80-
routeReducer: update,
85+
routeReducer: update
8186
};

0 commit comments

Comments
 (0)