Skip to content

Commit e271f55

Browse files
committed
Fix unsubscribe logic
1 parent 4bb250d commit e271f55

File tree

1 file changed

+17
-3
lines changed

1 file changed

+17
-3
lines changed

examples/real-world/syncHistoryWithStore.js

Lines changed: 17 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -87,9 +87,23 @@ export function syncHistoryWithStore(history, store, {
8787
return Object.assign({}, history, {
8888
// The listeners are subscribed to the store instead of history
8989
listen(listener) {
90-
return store.subscribe(() =>
91-
listener(getLocationInStore(true))
92-
)
90+
// History listeners expect a synchronous call
91+
listener(getLocationInStore(true))
92+
93+
// Keep track of whether we unsubscribed, as Redux store
94+
// only applies changes in subscriptions on next dispatch
95+
let unsubscribed = false
96+
const unsubscribeFromStore = store.subscribe(() => {
97+
if (!unsubscribed) {
98+
listener(getLocationInStore(true))
99+
}
100+
})
101+
102+
// Let user unsubscribe later
103+
return () => {
104+
unsubscribed = true
105+
unsubscribeFromStore()
106+
}
93107
},
94108

95109
// It also provides a way to destroy internal listeners

0 commit comments

Comments
 (0)