CodeConnoisseur
CodeConnoisseur

Reputation: 1869

Vue warn]: You may have an infinite update loop in a component render function

Getting an infinite loop error when looping through <a> attributes in vue.js. I have a method that loops through and adds attributes dynamically but when I use the method by binding it to an attribute in the <a> I get the error from the title. The attributes are a nested object within the original products array of objects.

Vue Code

<template>
  <div>
    <p>
      <a
        v-for="product in products"
        :href="product.product_url"
        type="submit"
        v-bind:additionalAttrs="addAttributes()"
      >
        Click Me
      </a>
    </p>
  </div>
</template>

<script>
export default {
data () {
    return {
      addedAttributes: [],
    };
  },
props: {
    products: Array,
  },
methods: {
    addAttributes() {
      this.products.forEach(product => {
          for (const [key, value] of Object.entries(product.attributes)) {
            this.addedAttributes.push(`${key}: ${value}`);
        }
      });
    }
  }
}
</script>

Upvotes: 0

Views: 2158

Answers (1)

Anatoly
Anatoly

Reputation: 22758

You use a method call to pass its result to additionalAttrs prop but it's not reactive and potentially can be called as many times as you have elements in products array

You just need one computed prop instead of an array and a method because they simply depend on products prop:

<a
  v-for="product in products"
  :href="product.product_url"
  type="submit"
  v-bind:additionalAttrs="addedAttributes"
>
Click Me
</a>
computed: {
  addedAttributes() {
      const addedAttributes = []
      this.products.forEach(product => {
          for (const [key, value] of Object.entries(product.attributes)) {
            addedAttributes.push(`${key}: ${value}`);
        }
      });
      return addedAttributes
    }
}

Upvotes: 1

Related Questions