Categories
Vue Answers

How to Auto-Reload or Refresh Data with a Timer in Vue.js?

Spread the love

Sometimes, we want to auto-reload or refresh data with a timer in Vue.js.

In this article, we’ll look at how to auto-reload or refresh data with a timer in Vue.js.

Auto-Reload or Refresh Data with a Timer in Vue.js

To auto-reload or refresh data with a timer in Vue.js, we can use the setInterval method.

For instance, we can write:

<template>  
  <div id="app">  
    {{ answer }}  
  </div>  
</template>  
<script>  
export default {  
  name: "App",  
  data() {  
    return {  
      answer: {},  
      timer: "",  
    };  
  },  
  created() {  
    this.fetchData();  
    this.timer = setInterval(this.fetchData, 5000);  
  },  
  methods: {  
    async fetchData() {  
      const res = await fetch("https://yesno.wtf/api");  
      const data = await res.json();  
      this.answer = data;  
    },  
    cancelAutoUpdate() {  
      clearInterval(this.timer);  
    },  
  },  
  beforeDestroy() {  
    this.cancelAutoUpdate();  
  },  
};  
</script>

We have the fetchData method that gets data from an API.

And we create the timer with the setInterval in the created hook.

We also call fetchData to get the initial data.

We pass in this.fetchData to run it periodically.

And we specify the period to be 5000 milliseconds.

In the besforeDestroy hook, we call cancelAutoUpdate to call clearInterval to clear the timer so that the timer is removed when we unmount the component so it’ll stop running.

In the template, we render the answer .

Conclusion

To auto-reload or refresh data with a timer in Vue.js, we can use the setInterval method.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *