I'd like to persist some user data to localStorage and need for the store to subscibe to state change but I don't want to fire each time the state changes but rather only when a particular event happens as in my case a user_update event.
Any ways can I have the store to subscribe to a specific event instead of the generic:
store.subscribe(()=>{
//save to local storage here
})
Well thanks heaps for your help :)
When you are subscribing to the store, your inner function will fire every time something in store changes. That is the way it meant to be by design. So, you cant respond to event, but you can respond to changes in particular part of the store.
function observeStore(store, select, onChange) {
let currentState;
function handleChange() {
let nextState = select(store.getState());
if (nextState !== currentState) {
currentState = nextState;
onChange(currentState);
}
}
let unsubscribe = store.subscribe(handleChange);
handleChange();
return unsubscribe;
}
Then do observeStore(store, select, this.writeToLocalStorageOrWhatever)
. By the way, for persisting store data in local storage try to use redux-persist.
Check this for more: Redux store API Discussion
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With