Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redux Store to subscribe to a particular event only? store.subscribe()

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 :)

like image 331
Fabrice Avatar asked Dec 25 '17 09:12

Fabrice


1 Answers

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

like image 142
Andy Theos Avatar answered Oct 01 '22 02:10

Andy Theos