0

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?

Gayrat Vlasov
  • 159
  • 2
  • 5
  • When you've added tags, it is redundant and unnecessary to include that same information in the title or post body. The tag system works extremely well here, and does not need additional help. The tags alone will suffice. The redundancy is just noise and clutter. – Ken White May 01 '21 at 20:38

1 Answers1

1

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.

  • Thank you! I asked the wrong question :) VUE 3 say: to save reactivity in VUE3 state: https://v3.vuejs.org/guide/list.html#mutation-methods you have to use this methods: push() splice() ... I'm using the method from example 2 in my VUEX4 and I'm lost reactivity. Yes, VUEX don't use alone in composition API and it combines with compute global API Am I correct to understand - VUEX doesn't have reactivity itself and I must add reactivity inside my component using compute? – Gayrat Vlasov May 02 '21 at 04:50