Is setting value of the localStorage a side effect

2019-07-09 05:13发布

问题:

I'm working on a React+Redux app that must save certain values from the store to localStorage. I have some utility function, that securely store values to localStorage. I have an action (thunk) and reducer.

const wallet = (state = getFromLocalStorage('wallet'), action) => {
  switch(action.type) {
    case 'SET_WALLET':
      setToLocalStorage('wallet', action.payload); // <--- **SIDE EFFECT?**
      retrun action.payload;
    default:
      return state;
  }
}

Reducers must be pure functions. Does the getToLocalStorage function call break the purity of the reducer? And if so, where is the proper place to call this function?

回答1:

As the other comment stated: yes, it's definitely a side effect. Now, it's probably not going to break anything in this case, but a reducer isn't the right place for that.

A better solution would be to either do this in a store subscription callback or a middleware. Or, even better, use one of the many store persistence libraries already available. Doing so in a thunk would also be an acceptable option, especially if you just want to persist a small amount of data rather than the entire store state.



回答2:

It's definitely a side effect in FP terms, but actually there is nothing bad with your code. There is no other better workaround of sharing your state between components (or even outside react.js tree) except redux/flux maybe.

Functional programming is a good thing but you don't need to turn that into cult