What is the correct pattern to mutate the state represented by an array?

109 Views Asked by At

What is the correct pattern to mutate the state represented by an array?

In a standard example for Vuex 4: VUEX4 GitHub example1

It is proposed to delete an array element and insert a new one.

 state.todos.splice(index, 1, {
      ...todo,
      text,
      done,
    });

Is this the standard pattern for changing the store array for Vuex 4, Vue 3?

Another example directly modifies an object field in an array: VUEX4 GitHub example2

   const cartItem = state.items.find(item => item.id === id)
   cartItem.quantity++

What's the right way to mutate the state's array in Vuex 4 without reactivity lost? Is it possible to direct array's item modification by index as example2? Is VUEX4 have reactivity - or reactivity is the only component's property?

1

There are 1 best solutions below

1
On

There's no convention. Treat Vuex as just javscript. In the first example you've shown, the author is doing it that way because it's the most convenient way to do so.

This is the highest rated answer for inserting an element at index: How to insert an item into an array at a specific index (JavaScript)?, which is what example 1 is doing.

Perhaps you're confused since Vue 2 had reactivity caveats and the .splice example would possibly not be reactive. Vue 3 doesn't have the reactivity caveats Vue 2 had.