How to do polling with VueJS

What is Polling?

The web (or HTTP 1.1 to be correct) is build on top of request – response cycle, in this way of communication though the server can’t send updates to the client when data changes, unless the client makes a request. “Polling” is the action of periodically requesting a given resource to check for changes. Very handy in reactive apps, where we want to seamlessly update the data.

How to do polling in Vue.JS?

I’ll give you a very simple implementation of polling in Vue.JS which I’m using all the time and it seems to be working flawlessly so far.

new Vue({
  el: '#pollingExample',
  data: {
    discountedProducts: []
  },
  methods: {
    loadData: function () {
      $.get('/store/discounts', function (response) {
        this.discountedProducts = response.discountedProducts;
      }.bind(this));
    }
  },
  mounted: function () {
    //Initial Load
    this.loadData();
    //Run every 30 seconds
   var loadData = function(){
        this.loadData();
        // Do stuff
        setTimeout(loadData, 30000);
   };
     setTimeout(loadData,30000);
  }
});

<div id="pollingExample">
  <div v-for="product in discountedProducts">{{ product.name + "-" +product.price + "$" }}</div>
</div>

There is nothing special in the code above, I simply create a function that loads the data(loadData), and the more interesting part is hooking into the mounted function, which is a built in method called right after the instance has been mounted. That is our magic bullet right there, when the instance is mounted we load the data initially and with the help of setInterval we schedule our function to run every 30 seconds.
This is how you do polling in Vue.JS with just a few simple steps.

About Pavel Petrov 2 Articles |  21 How-tos
Pavel is a senior developer for the last 7 years, with extended interest in Linux administration, WordPress and Symfony.

3 Comments

Leave a Reply

Your email address will not be published.


*