A
A
andrei_pro2019-06-16 00:06:16
JavaScript
andrei_pro, 2019-06-16 00:06:16

How to properly update nested object?

Hello.
vuex has an object:

store: {
      product: {
          name: 'Product',
          options: {
              isFree: false,
              delivery: true
          }
      }
   }

there is a mutation to update:
updateProduct(state, {product, data}) {
    Object.assign(product, data)
}

Then I update one option:
const product = this.product

this.$store.commit('updateProduct', {
   product,
   data: {
      options: {
         isFree: true,
      }
   }
}

Problem: The rest of the options are removed from the object.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
0
0xD34F, 2019-06-16
@andrei_pro

Pass not the entire object to the mutation, but only the part of it that you are going to update:

this.$store.commit('updateProduct', {
  product: product.options,
  data: {
    isFree: true,
  },
});

Otherwise, you must recursively merge the properties of the objects. If you are not ready to implement this yourself, take the finished one .

A
alex_kulkoff, 2019-06-16
@alex_kulkoff

Isn't it possible to write a mutation to change an option and call it when needed?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question