Daniel You
Daniel You

Reputation: 33

Update DOM after fetching from API in VueJS

I am having troubles updating the DOM after fetching from an API.

My object is fetching the data correctly but the DOM is being rendered before and it won't update after receiving the API Data, I can't seem to understand why is not updating itself.

Here is my code:

<template>
  <div>
    <h1>Weather</h1>
    {{ weather }} 
  </div>
</template>

<script>
export default {
  name: 'Weather',

data() {
    return {
      weather : {},
    }

  },
  created() {
      this.getWeather()
  },

  methods: {
    async getWeather() {
      let self = this;
          try {
            const response = await fetch('https://api.weatherbit.io/v2.0/current?city=Berlin&country=DE&key=KEY');
            const myJson = await response.json();
            self.weather.temp = myJson.data[0].temp;
            self.weather.sensation = myJson.data[0].app_temp;
            self.weather.description = myJson.data[0].weather.description;
        } catch (error) {
            console.error(error);
        }
    }

</script>

Upvotes: 0

Views: 1664

Answers (2)

Furqan Ansari
Furqan Ansari

Reputation: 150

You should assign the response value to the weather property directly like this.

methods: {
   async getWeather() {
     let self = this;
         try {
           const response = await fetch('https://api.weatherbit.io/v2.0/current?city=Berlin&country=DE&key=dcbea1b771ab41f09cd6b138d8cd50c2');
           const myJson = await response.json();
           self.weather = myJson.data[0].temp;
           console.log(self.weather);
       } catch (error) {
           console.error(error);
       }
   }
 }

Here is the working example.

https://jsfiddle.net/srfpw785/

Upvotes: 2

Marin Terziyski
Marin Terziyski

Reputation: 221

I think you should insert your logic inside mounted() , not in created() , this should fix your problem with rendering.

<template>
  <div>
    <h1>Weather</h1>
    {{ weather }} 
  </div>
</template>

<script>
export default {
  name: 'Weather',

data() {
    return {
      weather : {},
    }

  },
  mounted() {
      this.getWeather()
  },

  methods: {
    async getWeather() {
      let self = this;
          try {
            const response = await fetch('https://api.weatherbit.io/v2.0/current?city=Berlin&country=DE&key=dcbea1b771ab41f09cd6b138d8cd50c2');
            const myJson = await response.json();
            self.weather.temp = myJson.data[0].temp;
            self.weather.sensation = myJson.data[0].app_temp;
            self.weather.description = myJson.data[0].weather.description;
        } catch (error) {
            console.error(error);
        }
    }

</script>

These are the steps in Vue lifecycle :

beforCreate, created, beforeMount, mounted, beforeUpdate, updated, beforeDestroy, destroyed

Hope this will help you to understand Vue lifecycle :)

Upvotes: 1

Related Questions