Vuex: Dispatch a function every 2 seconds only when a store property exists?

Viewed 656

I am trying to run a function that makes a GET request to update the quantity of a product but only when the currentProduct store property exists. If there's no selected product, then I don't want to have the interval be firing a function for no reason.

In pseudo code, I basically to say:

if $this.store.getters['myStore/getCurrentProduct']
then setInterval(this.$store.dispatch('updateQuantity'), 2000);

My only thought was to make a computed property for currentProduct:

computed: {
     currentProd() {
         return $this.store.getters['myStore/getCurrentProduct'];
     }
}

and then watch it :

watch: {
     currentProd(newVal,oldVal) {
          if (newVal != null) {
              let foo = setInterval(this.$store.dispatch('updateQuantity'), 2000);
          }
     } 
}

I'm just not sure how to keep this from overlapping and having a ton of intervals firing off

1 Answers

You should store the interval object in one place so you can reset it easily, instead of creating a new local interval in the function every time the watcher runs:

data () {
  return {
    productCheckInterval: null
  }
},
watch: {
  currentProd (newVal, oldVal) {
    clearInterval(this.productCheckInterval)
    if (newVal !== null) {
      this.productCheckInterval = setInterval(() => {
        this.$store.dispatch('updateQuantity')
      }, 2000)
    }
  } 
}
Related