In issue 303 in the Redux repo, Dan Abramov gives an example of a function that can wrap a store’s subscribe method in order to pass the previous state to the subscriber.
function observeStore(store, select, onChange) {
let currentState;
function handleChange() {
let nextState = select(store.getState());
if (nextState !== currentState) {
currentState = nextState;
onChange(currentState);
}
}
let unsubscribe = store.subscribe(handleChange);
handleChange();
return unsubscribe;
}
For some reason, this doesn't work for me. The first time my onChange handler is called currentState is undefined, as I’d expect. However, on each subsequent state change, the properties of currentState are equivalent in value (==) to those of nextState. The two state objects aren’t the same object, though because nextState === currentState evaluates to false.
I’m likely missing something really obvious. How do I capture the previous state in a closure?