Skip to content

Instantly share code, notes, and snippets.

@barnslig
Last active June 19, 2019 13:30
Show Gist options
  • Save barnslig/8f342d89d197977e3ebf5239e374fc17 to your computer and use it in GitHub Desktop.
Save barnslig/8f342d89d197977e3ebf5239e374fc17 to your computer and use it in GitHub Desktop.
Subscribe to changes of part of a redux tree
import get from "lodash.get";
import isEqual from "lodash.isequal";
/**
* Subscribe to changes of part of a redux tree
*
* @example
* watch(Store, "dataset.currentId", id => {
* console.log(id);
* });
* @param {Redux.Store} Store - Redux store created with createStore()
* @param {string} path - The path of the property to watch
* @param {function} cb - Callback that is executed on change with (cur, prev)
* @returns {void}
*/
const watch = (Store, path, cb) => {
let currentState;
Store.subscribe(() => {
let prevState = currentState;
currentState = get(Store.getState(), path);
if (!isEqual(prevState, currentState)) {
cb(currentState, prevState);
}
});
};
export default watch;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment