Search code examples
vue.jslaravel-5.3vuejs2

Vue 2 Laravel 5.3 Infinte Update Loop


There is no console log error but anything that I put in updated() hook [in the current code getCartItems/] will be rendered infinitely for some reasons that I do not know. even I set it as alert('hi') and it alert it infinitely. So I suspect something makes the project keeps updating values or something but I do not know where. Can anyone give me a suggestion to check where the problem is?

Cart-dropdown.vue

<template>
    <div class="row">
        <div class="col-md-12">
            <div class="row cart-dropdown-row" v-for="cart in carts">
                <div class="col-md-3">
                    <div class="cart-dropdown-img-wrapper">
                    <img class="d-flex align-self-center cart-dropdown-img" :src="cart.product_choice.img1" alt="Generic placeholder image">
                  </div>
              </div>
              <div class="col-md-6 cart-dropdown-info-wrapper">
                <h6 class="cart-dropdown-info">{{cart.product.name}}</h6>
              </div>
              <div class="col-md-3 cart-dropdown-qty-wrapper">
                <div class="cart-dropdown-qty">x{{cart.qty}}</div>
              </div>
            </div>
      </div>
    <div class="row">

    </div>
      <div class="row cart-dropdown-checkout-wrapper">
            <button type="button" class="btn btn-success btn-sm cart-dropdown-checkout" @click.prevent="goCheckout()">Check Out</button>
      </div>
  </div>
</template>

<script>
  export default {
    data(){
      return{
        carts:{},
      }
    },
    props:[
    ],
    mounted(){
      this.getCartItems()
    },
    updated(){
      this.getCartItems()
    },
    methods:{
        getCartItems(){
            var vm = this
        vm.$http.get('/getCartItems/').then((response)=>{
          vm.carts = response.data
        });
        },
        goCheckout(){
        window.location.href = 'http://localhost:8000/cart'
        }
    },
    computed:{
    }
  }
</script>

Solution

  • You are updating the vue instance data variable carts in the updated hooks and as docs says: updated hook is called after a data change causes the virtual DOM to be re-rendered and patched. So you are in a infinite loop: you change the vue data it updates the the DOM and call the updated block which again change the data.

    This is also mention in the docs:

    you can perform DOM-dependent operations in this hook. However, in most cases you should avoid changing state in this hook, because it may lead to an infinite update loop.

    You can see this circle in the below vue instance lifecycle diagram.

    enter image description here