npm install --save redux-observe
import observe from 'redux-observe';
observe(store, state => state.users, (userState) => console.log('Users changed!'));
observe(store, selector, onChange)
Observe runs the onChange
function each time the selected state from selector
changes.
store
store instanceselector
(Function): A selector function that will receive state and return a state slice that should be listened to for changes,(state) => stateSlice
onChange
(Function): A onChange function that will be called each time the state slice created from theselector
function changes,(stateSlice, dispatch) => {}
observe(store, state => state.users, (userState, dispatch) => {
forEach(userState.allIds, id => {
fetch(`/user/detail/${id}`)
.then(r => r.json())
.then(data => dispatch({type: 'USER_DETAILS', payload: data}))
})
});
Tips:
- It will often make sense to extract
onChange
functions so that they are not defined inline. - It is possible to get into an infinite loop - careful with dispatches!