Home > Blockchain >  What is the common way to encapsulate data inside Pinia stores when using the composition API?
What is the common way to encapsulate data inside Pinia stores when using the composition API?

Time:03-10

I'm using Vue 3 with Pinia and want to use the composition API inside my Pinia stores. Given the following example store

export const useMyStore = defineStore("my", () => {
    const currentState = ref(0);

    return { currentState };
  }
);

I can directly modify the value of currentState. I'm not sure if this is the way to go or if I should prevent this and provide some get and set functions like

export const useMyStore = defineStore("my", () => {
    const currentState = ref(false);

    const readonlyCurrentState = computed((): Readonly<boolean> => currentState.value);

    function changeState(newState: boolean) {
        currentState.value = newState;
    }

    return { readonlyCurrentState, changeState };
  }
);

The options API solves by problem by providing getters and actions, so I thought if I should achieve the same here.

This might be an opinion based question but I would like to know if I should encapsulate the state currentState to prevent corruption by accident.

CodePudding user response:

I can directly modify the value of currentState

Yes, this is intentional. As described in comparison with Vuex

mutations no longer exist. They were very often perceived as extremely verbose. They initially brought devtools integration but that is no longer an issue.

This is more technical reason but you can read more from author himself (and people who doesn't like this new "freedom") in this discussion: Add an option to disallow direct state modification from component

Generally the code in your question demonstrates the point perfectly - lot of unnecessary code just to change simple boolean value. Of course there are cases where data is more complex, you want to enforce some constraints etc. where unrestricted direct mutation can be considered dangerous. I think the pattern in your question is perfectly viable and you can find more ideas (and experimental "strict mode" support commit waiting for feedback) in the linked discussion

Personally I think a lot of the safety checks can be done with linting and especially TypeScript definitions. You get the additional safety during development without paying the price at runtime (in terms of additional code executing and being bundled&served). Great thing about Pinia is that it gives us the choice of how to approach the problem...

  • Related