Home > Mobile >  Vue.js render new data from API call
Vue.js render new data from API call

Time:10-05

I am making a weather app written in Vue.js, which fetches weather data periodically, but I have an issue rendering new data after the initial API call.

The empty data array is declared in the data, and a timer is used to fetch new data, as such:

      data() {
        return {
          weatherData: [],
          timer: '',
    };
  },

I have declared the data fetching in methods, as such:

methods: {
    async fetchWeatherData() {
      const response = await fetch("http://localhost:5002/timeseries");
      const data = await response.json();
      if (response.ok) {
        console.log("Data fetched sucssefully!");
      }
      return data;
    },

And when the app loads, the fetchWeatherData and setInterval is initiated:

  async created() {
     this.weatherData = await this.fetchWeatherData();
     setInterval(() => this.timer = this.fetchWeatherData(), 10000)

  },

The problem is that the new data is not rendered to the DOM, although new data is fetched successfully.

What would be the best step to ensure that the new data is rendered correctly upon successfull fetch?

-HK

CodePudding user response:

In the component (or any container) where you render the weather data, add a key (like :key="renderWeatherKey"). Add renderWeatherKey to component data.

data() {
        return {
          weatherData: [],
          timer: '',
          renderWeatherKey: 0
    };
  },

In the method fetchWeatherData(), inside 'if' condition, add this.renderWeatherKey :

async fetchWeatherData() {
      const response = await fetch("http://localhost:5002/timeseries");
      const data = await response.json();
      if (response.ok) {
        console.log("Data fetched sucssefully!");
        this.renderWeatherKey  
      }
      return data;
    },

You can force the re rendered with that.

CodePudding user response:

The solution, as posted by James Thomson over at the Vue forum, was to set the setInterval to async, since the fetch method also is async. See the full answer here.

  • Related