SheppardPL
SheppardPL

Reputation: 85

VUEX API layer in mutation or getter?

Let's say I have a response from API:

{
   name: 'Mat',
   last_name: 'Kowalsky',
}

and interface for Person looks like:

{
    name: string;
    lastName: string;
    children: Person[]
}

Where is the best place to transform one model into another? Should I do this in mutation like that:

 const setPerson: (state: State, person: any) => {
     state.person = {
        name: person.name,
        lastName: person.last_name,
        children: (person.children) ? person.children : []
     } 
  }

or maybe in getter like that:

   const getters = {
      person: (state: State) => {
         return {
             name: state.person.name,
             lastName: state.person.last_name,
             children: (state.person.children) ? state.person.children : []
         }
      }

   }

Regards

Upvotes: 1

Views: 108

Answers (3)

santanu bera
santanu bera

Reputation: 1311

As you are using Response, you should use mutation. As it doesn't depends on any store properties.

Getters are those which depends on another store property and when the store property changes, getters changes automatically. So, if your property have the dependencies to other properties of your store, then it is always better to use getters

Upvotes: 0

mickaelw
mickaelw

Reputation: 1513

If I must choice, that's be the mutation but I think the best way, because your store is dependant of your api.

You can map the response of the API to your Person like that your mutation already has a Person object.

With Promise:

myPromise.then(res => ({ res.name, lastName: res.last_name }))

With Rxjs:

myObservable.pipe(
   map(res => ({ res.name, lastName: res.last_name }))
)

Upvotes: 0

Thomas
Thomas

Reputation: 2536

The mutation is called once when inserting the new persons. The getter is most likely called often.

That's why i would put the transformation in the mutation.

Upvotes: 1

Related Questions