0

I'm getting this error in my console

[Vue warn]: Avoid mutating a prop directly since the value will be overwritten whenever the parent component re-renders. Instead, use a data or computed property based on the prop's value. Prop being mutated: "catProducts"

Here is my vue component

  <template>
    <div>
      <table class="table table-striped">
          <thead>
              <tr>
                  <th>Product Name</th>
                  <th>Remove</th>
              </tr>
          </thead>

          <tbody>
              <tr v-for="product in catProducts">
                  <td>
                      {{ product.name }}
                  </td>
                  <td>
                      <button @click="remove(product)" class="btn btn-danger">Remove</button>
                  </td>
              </tr>
          </tbody>
      </table>
    </div>
  </template>

  <script>
    export default{ 
      props: ['category', 'catProducts'],
      data(){
        return {
          
        }
      },
      methods: {
        remove(product){
          axios.delete('/category/products/'+this.category.id+'/'+product.id).then(response => {
            this.catProducts = response.data.products;
          });
        }
      }
    }
  </script>

what response.data.products; returns is all the products that belong to that category. Even though my code does what it supposed to do in terms of it deletes the product for that category, I do still get the Avoid mutating a prop error in my console and I'm not sure how to fix it.

Aurilie
  • 189
  • 3
  • 14

2 Answers2

1

There are two things here that go wrong:

  1. Changing/mutating the prop catProducts directly

Solution: emit an event like 'deleteProduct' to a parent components so that it can call axios.delete and then fetch a refreshed list of products and overwrite a list of products that is passed as a prop to a child component.

  1. Returning new product list from HTTP DELETE method.

Solution: call axios.delete and if it's successful then call axios.get to get a list of products and overwrite a list of products that is passed as a prop to a child component.

Anatoly
  • 20,799
  • 3
  • 28
  • 42
0
  1. After the delete call finishes
remove(product){
  axios.delete('/category/products/'+this.category.id+'/'+product.id).then(response => {
    this.catProducts = response.data.products;
    }
  );
}

Instead of mutating the prop directly emit an update event so you can use sync modifier in the parent component to update the prop.

remove(product){
  axios.delete('/category/products/'+this.category.id+'/'+product.id).then(response => {
    this.$emit("update:catProducts", response.data.products);
    }
  );
}

Then in the parent component if catProducts is component's state.

<CatProductsRender :catProducts.sync="catProducts" />
dsfx3d
  • 372
  • 2
  • 12