Hilo
Hilo

Reputation: 869

Vuex best practices for complex objects

My Vuex store contains objects with a variety of complexity. Some have nested objects, some have arrays of nest objects.

I could create generic function to mutate a specified property along the lines of:

setProperty(state,{ type, id, prop, value })
{
  state[type][id][prop] = value;
}

but that will quickly get complicated for nested object, arrays of objects. It also seems very tedious to have to create a mutation for every single object property, nested or otherwise.

What are the best practices for creating mutations to modify objects, nested objects, arrays, etc?

Another related issue, is it considered bad form to pass the objects into the mutations as opposed to looking them up in the state:

setProperty(state,{ obj, prop, value })
{
  obj[prop] = value;
}

Upvotes: 15

Views: 6572

Answers (1)

Kia Ishii
Kia Ishii

Reputation: 146

Generally speaking, it is best if you just could avoid nested state structure at first place. I'm not sure how your data are structured, but if you're doing that because you have relationship between those object or area of object, it might be worth trying normalizing the state shape.

Here is the good article from Redux author. It's talking about Redux but the core concept is very same for the Vuex. https://redux.js.org/docs/recipes/reducers/NormalizingStateShape.html

And the Vues ORM is a library that do that for you automatically.

Upvotes: 9

Related Questions