Reputation: 1839
So I have been following the tutorial to make redux state persist to the local storage. https://egghead.io/lessons/javascript-redux-persisting-the-state-to-the-local-storage
However, what if I create my store like this with reducers:
const store = createStore(rootReducer, initialState)
And the root reducer is a combined reducers of:
const rootReducer = combineReducers({
auth: AuthStore,
content: contentReducer,
pages: pageReducer,
}
And each reducer has its own state/initialState, for example contentReducer is constructed as below:
const initialState = {selected, search}
const contentReducer = (state = initialState, action) => {
switch (action) {
case SELECT :
return {
...state,
selected: action.payload
case SEARCH:
return {
...state,
search: action.payload
}
}
}
If I follow the tutorial, then I can do
const saveSelected = (state) => {
try {
const serializedSelected = JSON.stringify(state);
localStorage.setItem('selected', serializedSelected)
} catch (err){
console.log(err)
}
}
store.subscribe(() => {
saveSelected(store.getState().content.selected)
})
However since I have many more reducers (I am only giving some examples above)and thus there are many actions dispatched to the store, I don't want the store to keep firing subscribe function everytime when any action is dispatched. I only want the store to subscribe to changes when the particular store.getState().content.selected
is updated. How can I do that?
Upvotes: 0
Views: 362
Reputation: 1584
You can use a Redux middleware, which lets you register a function that's being called on each dispatch
. You get a reference to the store object, so that you can check store.getState().content.selected
state and act accordingly. See more details and examples here.
Upvotes: 0