[Vuejs]-Call API endpoint repeatedly in some pages for dispatch an Vuex action

0๐Ÿ‘

I believe the less bad thing is to do a mixin which exposes 3 things:

  • startPolling() :
    method that starts polling on the particular component

  • stopPolling() :
    method that stops polling in the component

  • pollingprop() //name it as you see fit
    computed property that always exposes the updated data, this data is calculated every time you make the call inside the mixin

  • (optional) hooks beforeRouteEnter() + beforeRouteLeave() docs
    which automatically calls the this.startPolling() and the this.stopPolling()

0๐Ÿ‘

For solving this problem I used mixin and it became a fine solution.

I create a mixin like this:

// intervalMixin.js
export default {
  data: () => {
    return {
     getting: null,
    };
  },
  computed: {
    ...mapActions({
      myAction: "***name-of-action***",
    }),
  },
  created() {
    this.getData();
  },
  beforeDestroy() {
    clearInterval(this.getting);
  },
  methods: {
    getData() {
      this.getting = setInterval(() => {
        this.myAction()
      }, 30000);
    },
  },
}

So I add this mixin to each component I want like this:

mixins: [intervalMixin],

Leave a comment