Refreshing the DOM following an API call using VueJS

Struggling with updating the DOM after fetching data from an API.

Although my object is successfully fetching the data, the DOM renders before receiving the API Data and fails to update afterward. I'm puzzled as to why it's not refreshing itself.

Check out my code snippet below:

<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>

Answer №1

To update the weather property with the response value, assign it directly in your code.

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);
       }
   }
 }

See the working demo to understand better.

https://jsfiddle.net/srfpw785/

Answer №2

To resolve the issue with rendering, I recommend moving your logic from created() to mounted(). This simple adjustment should fix any problems you are experiencing.

<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>

If you're curious about the Vue lifecycle, here are the steps in order:

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

I hope this information helps you better understand the Vue lifecycle!

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Unexpected behavior encountered when implementing specific Textfield validation with Material UI

Currently running a project on Node and utilizing React for the front-end, I have encountered an issue with setting .env variables. The project is built with Material UI, and most TextFields are working as expected with their specified validation rules. ...

What is the proper way to transfer information to my ajax function from my controller?

I need to dynamically update an element on my webpage based on server-side code events. For example, when I trigger the "Start" function by clicking a button, I want the text inside a specific element to change to "Downloading", and then once the process i ...

Steps to Utilize Google Apps Script from a Website

I've been on a mission to find the solution to my problem. I have a basic web page with HTML/CSS/JS. What I want is for users to visit the page and immediately have it call up a Google script I created, which will pull information from a spreadsheet a ...

Loop Swig with Node.js and Express!

I'm attempting to create a loop in order to access array objects using swig. The goal is to make a loop that checks the object's length. I am able to access the objects by {{styles[0].style}}, where [] represents an array. So, essentially what I ...

What is the best way to transfer variables between PHP and an external JavaScript file?

I need to transfer 2 variables (which store data for a chart) to an external JS file that contains the chart settings. In my PHP code, I have: <script type='text/javascript'> var final_values = '$final_values'; var final_names = ...

JavaScript codes within HTML elements may not be functional when using an AJAX loader to transition to the next page

I'm experiencing issues with an ajax loader in Wordpress. The theme I am using has an ajax loader button that is interfering with my inline script. Despite reading over 10 articles on the problem, I haven't been able to find a solution yet. Do ...

Issue with Ionic ng-click not triggering

I am currently experimenting with an Ionic application that utilizes a Firebase backend. The issue I'm facing is that the ng-click="loginUser(user)" function does not seem to be triggering. When checking the console, it only displays Signed Out from ...

Upon the initial rendering, Next.js obtains access to the query { amp: undefined }

When using Next.js 9.3, I encountered an issue where I needed to access the query on initial render and pass the result of the query to next/head in order to change the title and description of the page. The component is receiving the query from the useRo ...

What is the best way to create a loop within a JavaScript function?

I'm having some trouble with looping inside a function. It seems like my looping is not working properly and I need help fixing it, along with suggestions for the problem. :) Here's what I've tried: <script> function getImage1( ...

What is the best method for storing and accessing audio files that users upload in my MERN application?

I am developing a MERN application and am looking to implement a feature that allows users to upload audio files. I have read that storing the files directly in the database or within a folder inside the app is not recommended. I need a solution that en ...

There was a problem with the WebSocket handshake: the response header value for 'Sec-WebSocket-Protocol' did not match any of the values sent

I've encountered an issue with my React project that involves streaming live video through a WebSocket. Whenever the camera firmware is updated, I face an error in establishing the WebSocket connection. Here's how I initiate the WebSocket: wsRe ...

Master the Art of Scrollbar Control in Angular!

I am currently developing a chat web application that functions similar to gchat. One of the key features I'm trying to implement is an alert notification when the scrollbar is in the middle of the div, indicating a new message. If the scrollbar is at ...

Continuously decrease a sequence of identical numbers in an array through recursion

One of the key challenges was to condense an array of numbers (with consecutive duplicates) by combining neighboring duplicates: const sumClones = (numbers) => { if (Array.isArray(numbers)) { return numbers.reduce((acc, elem, i, arr) => { if ( ...

Process executes another process

Can anyone assist me with a JavaScript inquiry? I am curious if it is feasible to implement this: variable: { info1: 'info1', info2: 'info2', show: false, someNameFunction: functionWhichIWantRun(row) } So, after defining the var ...

Display an error message if the input field is empty, then conceal the message once the input field is filled

Can anyone assist with a Vue.js app issue I'm facing? Currently, when the search input is empty, an error message appears - which is okay. However, I want to hide this error message as soon as the user starts typing in the search field. The code for m ...

showing the response message from a post request using Vue.js and Axios

Within APIService.js, there's a function: createPatient(data){ const url = 'http://192.168.1.3/api/clinic/patient/add/'; return axios.post(url, data).then(resp => {return resp}); } In the script tag of my vue component: result ...

Unable to add JSON data to Javascript List Object? Consider using a combination of Node.JS and Firebase for a

router.get('/getMeals',function(req,res){ var mealsList = []; mealsList.push("bar"); mealsRef.on("value",function(data){ data.forEach(function(child){ console.log(child.val()); var newMeal = child ...

"Trouble arises when dealing with nested object arrays in Formik and handling changes in a child

I am struggling with passing a value to handleChange in formik validation. To address this issue, I created a component whose quantity is dynamically added based on the number of numChild. My goal is to allow users to click an icon and add any number of sk ...

Adding navigation buttons to a Material-UI Select component: A step-by-step guide

Currently, I have integrated a Select component from MUI and it is functioning well. When an item is selected from the list, the router automatically navigates to that location: This is the snippet of code being used: export default function SelectLocatio ...

CSS Flexibility

Greetings everyone, it's been a while since I dabbled in web development. I recently worked on my site with the intention of making it responsive using flexbox. This is my first time posting here, so please guide me on how to seek help more effective ...