Skip to content

Instantly share code, notes, and snippets.

@barnslig
Created April 19, 2020 19:39
Show Gist options
  • Save barnslig/f3c2126177c5a8200b471ce8344db860 to your computer and use it in GitHub Desktop.
Save barnslig/f3c2126177c5a8200b471ce8344db860 to your computer and use it in GitHub Desktop.
import get from 'lodash.get';
/**
* Subscribe partially to redux store changes
*
* @example
* subscribe(store, "backup.url", (state, prevState) => console.log("change!", state, prevState));
*
* @param {Redux.Store} store - Redux store
* @param {String} path - Path within the store object that should be watched for change. See https://lodash.com/docs/4.17.15#get
* @param {Function} cb(state, prevState) - Callback for when the store changes at the specified path
* @returns {void}
*/
const subscribe = (store, path, cb) => {
let state = get(store.getState(), path);
store.subscribe(() => {
const previousState = state;
state = get(store.getState(), path);
if (previousState !== state) {
cb(state, previousState);
}
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment