Search code examples
reduxstatevuexpinia

should actions in state management modify state directly?


I'm using pinia with vue3, but this question applies to all state management structure.

in actions, should I return the result then overwrite(or mutate) state or just modify state directly as a side-effect?

example1: return result then re-assign at component

const exampleStore = createStore({
  state: { someState: 1 },
  actions: {
    async getNewState() {
      const newState = await get();
      return newState;
    }
  }
});

//...then in some component in different file...
exampleStore.someState = await exampleStore.getNewState();

example2: modify state directly as a side-effect

const exampleStore = createStore({
  state: { someState: 1 },
  actions: {
    async getNewState() {
      const newState = await get();
      this.someState = newState; // assign directly as a side-effect
    }
  }
});

although both works fine, but I wanna know which approach is more recommended.


Solution

  • If you use example1, fill the state value in the component. I usually use example2, I don't need to fill the state value in the component. but I add one more function to reset the state value to back the initial value.