epeleg
epeleg

Reputation: 10945

shoud I use vuex getters even when no computation is involved?

If i just want to return a member of my vuex state, should I define a getter for it? or is it o.k. to use mapState ?
My dilemma is as follows:
1) It seems redundent to have a getter that simply returns a member of the state as in:

 getters: {
   user (state) {
   return state.user
   }
 }

when I can just use the following code in the consuming component and save the coding of the getter ?

computed: {
        ...mapState('auth',['user']),
}

However, if something did change in the future and I would like some computation done on the user object before it is returned then using a getter and

computed: {
        ...mapGetters('auth',['user']),
}

Would allow for a simpler change. But if this is the recommended way to go then why provide mapState to begin with?

So should I use getters for this type of simple state memeber access? or not?

Upvotes: 0

Views: 39

Answers (1)

acdcjunior
acdcjunior

Reputation: 135832

Technically, as you note, you can do either way. When there's no calculation involved, though, it becomes a matter of taste.

There's no authority in this, but I'd recommend as general advice:

If your application...

  • has a stablished state format AND
  • your state that doesn't tend to change AND
  • your application is not that big,

...then map to state.

Else, use getters.

In other words, if your application is somewhat small and should be stable, then, why not?

If else, other than the obvious "use getters when you need calculations", if your application:

  • tends to grow OR
  • has a state structure that is not stablished and tends to change OR
  • has deeply nested state.

Then use getters. They decouple you application from the state, allowing it to change more freely (which is frequently needed "in times of trouble"), simplifying refactoring a lot.

In other words,

when in doubt, use getters instead of mapping directly to state.


Note: IMO, this question is the same as using Selectors in Redux. And, in Redux, the usage of selectors is widely recommended.

Upvotes: 1

Related Questions