Last active
June 19, 2019 13:30
-
-
Save barnslig/8f342d89d197977e3ebf5239e374fc17 to your computer and use it in GitHub Desktop.
Subscribe to changes of part of a redux tree
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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