Skip to content

Instantly share code, notes, and snippets.

@mikkpr
Created September 6, 2017 13:56
Show Gist options
  • Save mikkpr/ed5b9d8ae183184ebafe8c723c61f091 to your computer and use it in GitHub Desktop.
Save mikkpr/ed5b9d8ae183184ebafe8c723c61f091 to your computer and use it in GitHub Desktop.
connectState that vaguely works like react-redux's `connect`
/* usage:
const dataSelector = state => {
return state.foo.bar;
}
connectState(dataSelector)((newValue, prevValue) => {
console.log('foo.bar changed from', prevValue, 'to', newValue);
});
*/
// const STORE = Redux.createStore(reducer);
connectState = dataSelector => {
let prevState;
return callback => {
// store initial state
let initState = dataSelector(window.appState.getState());
// subscribe returns the unsubscribe function, so we have to store this
var unsubscribe = STORE.subscribe(() => {
// get slice of latest state using the provided `dataSelector` function
let curState = dataSelector(STORE.getState());
// use lodash.isEqual or Immutable.is or some other form of object comparison
// if (slice of) state has changed, call the `callback` function with new and old states
if (!isEqual(curState, prevState)) {
callback(curState, prevState);
// store currentState
prevState = curState;
}
});
// initial call when binding subscriber, this is optional
callback(initState, prevState);
// store initial state
prevState = initState;
return unsubscribe;
};
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment