What is the best way to synchronize Vue data with the response from an axios request?

Is there a way to incorporate data retrieved from axios into vue js data?

value: [parseInt(this.maintemp1),parseInt( this.maintemp2)], <--------This is where I'm facing an issue

    export default {
  data: () => ({
    maincity: "",
    maintemp1: "",
    maintemp2: "",
    maindate1: "",
    showLabels: true,
    lineWidth: 2,
    labelSize: 7,
    radius: 10,
    padding: 8,
    lineCap: "round",
    gradient: gradients[5],
    value: [parseInt(this.maintemp1),parseInt( this.maintemp2)], <--------This is where I'm encountering a problem
    gradientDirection: "top",
    gradients,
    fill: true,
    type: "trend",
    autoLineWidth: false
  }),
  mounted() {
    axios
      .get(
        "http://api.openweathermap.org/data/2.5/forecast?q=khiva&units=metric&appid=myapi"
      )
      .then(response => {
        this.wholeResponse = response.data.Search;
        this.maincity = response.data.city.name;
        this.maindate1 = response.data.list[1].dt_txt;
        this.maintemp1 = response.data.list[1].main.temp;
        this.maintemp2 = response.data.list[9].main.temp;
      })
      .catch(error => {
        console.log(error);
      });
  }
};

Answer №1

The reason for this occurrence is that the values of the data option are evaluated before the mounted method is called. Therefore, when the initial value of value is set, both maintemp1 and maintemp2 are empty strings. Additionally, since value is not a computed property, it does not monitor changes to maintemp1 or maintemp2. One solution is to assign the value of value inside the axios .then() method.

To address this issue, first ensure that value is initialized as an empty array in the data section:

data: () => ({
  ...
  value: [],
    ..
}),

Then within the mounted method, update it accordingly:

axios
  .get(
    "http://api.openweathermap.org/data/2.5/forecast?q=khiva&units=metric&appid=myapi"
  )
  .then(response => {
    this.wholeResponse = response.data.Search;
    this.maincity = response.data.city.name;
    this.maindate1 = response.data.list[1].dt_txt;
    this.maintemp1 = response.data.list[1].main.temp;
    this.maintemp2 = response.data.list[9].main.temp;

    this.value = [parseInt(this.maintemp1), parseInt( this.maintemp2)];
  })
  .catch(error => {
    console.log(error);
  });

Answer №2

Your result is a calculated outcome. The info holds an array of fixed entities that could vary in your element as time goes by, but they only represent the values. If your outcome relies dynamically on other variables, it should be included in calculated like so:

export default {
  info: () => ({
    maincity: "",
    maintemp1: "",
    maintemp2: "",
    maindate1: "",
    showLabels: true,
    lineWidth: 2,
    labelSize: 7,
    radius: 10,
    padding: 8,
    lineCap: "round",
    gradient: gradients[5],
    gradientDirection: "top",
    gradients,
    fill: true,
    type: "trend",
    autoLineWidth: false
  }),
  calculated: {
     result() {
       return [parseInt(this.maintemp1),parseInt( this.maintemp2)],
     }
  },
  mounted() {
    axios
      .get(
        "http://api.openweathermap.org/data/2.5/forecast?q=khiva&units=metric&appid=myapi"
      )
      .then(response => {
        this.wholeResponse = response.data.Search;
        this.maincity = response.data.city.name;
        this.maindate1 = response.data.list[1].dt_txt;
        this.maintemp1 = response.data.list[1].main.temp;
        this.maintemp2 = response.data.list[9].main.temp;
      })
      .catch(error => {
        console.log(error);
      });
  }
};

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

Initial request fails to retrieve cookie generated by Javascript

I created a shopping cart that generates a cart, adds items, and stores it in a cookie named 'cart'. However, when I click on a hyperlink that leads to the checkout page, my ASP.NET application is unable to access the cookie. The cookie only get ...

The first instance of an object retains its class, but subsequent instances may change

Trying to articulate my query concisely is proving challenging. Let me do my best to provide a clear explanation. The fixed header on my website features 4 buttons. I've created a JavaScript file that alters the class of each button when clicked. The ...

Step by step guide on sending an array of objects along with files using FormData

Currently, I am attempting to use axios to send an array of objects to the backend (I am utilizing express.js). When I try to send the object without any files, everything works fine. However, as soon as I attempt to include files along with it, I encounte ...

Error: the function was not defined and has not been caught

In an effort to develop a quiz application, I am working on a feature that will increment a counter when the correct answer is selected. While I have identified the correct answer, I am struggling with implementing a method called correctTest to achieve th ...

Converting an array of Binding values to a Binding<[type]> instead of an array of Binding<type> in Swift/SwiftUI

I am facing an issue with extracting Binding values in the correct format from the dataModel. The error message I see in XCode is "Cannot convert value of type '[Binding<String?>]' to expected argument type 'Binding<[String]&g ...

Is there a way to trigger another API call when clicking a button in Vue.js?

I recently started using vue js and I am facing a challenge with this component. I am attempting to trigger another API call when one of the list options is clicked. <template> <div> <h1 class="text-center text-4xl font-bold">Our ...

Creating an interactive dropdown menu in React JS on click

My goal is to display a select tag when a text or div element is clicked. I'm unsure of the correct method and location to render it. Therefore, I decided to create a handler function that sets a variable, isItClick, to true in order to show the sele ...

Having trouble with the page layout in AngularJS

I am currently delving into Angular JS in order to fulfill some academic requirements. The issue I am facing is with the rendering of a landing page after successfully logging in through a login portal that caters to three types of users. Strange enough, w ...

Troubleshooting the sidebar pin-unpin problem using Jquery and CSS

I have created a single side panel that allows me to toggle between opening and closing the sidebar by hovering on it. I can also pin and unpin the sidebar by clicking on the pin image. Now, I want to open the sidebar onClick instead of onHover and remove ...

The debate between ensuring input validity and making fields mandatory on multi-page forms

I am currently working on a multi-page form and using jQuery Validate to validate it. The user has four options: next, prev, save, submit. Save, next, and prev all save the current page within the form; whereas submit is similar to save, but triggers addi ...

Struggling to set values for Player Object?

Being a novice programmer, I have a good understanding of initializing objects. However, I seem to be facing an error in this code that I just can't figure out. Can someone assist me with it? The line causing the issue is: Players player = new Players ...

Encountering an issue... invariant.js:42 Error: A `string` value was received instead of a function for the `onClick` listener

Currently, I am working on creating a form that allows users to build quizzes without any restrictions on the number of questions they must include. To achieve this, I plan to add an "add question" button at the bottom of the quiz form, allowing users to d ...

`Using Rollup to combine local typescript files into a single main bundle`

I'm currently working on developing an npm module that is intended for use in web browsers. For this project, I have chosen to utilize TypeScript and Rollup as my tools of choice. Here is a snippet of my tsconfig.json: { "compilerOptions": { " ...

How can I utilize a Vuex store to establish a default image?

I'm trying to set a default image for the user in vuex by configuring my vuex store like this state:{ default_image: "../assets/images/users/1.jpg" }, getters:{ Image:state=>state.default_image, } Next, I have the App.vue file <templ ...

The concept of matryoshka logic applied to data manipulation

"mainData"{ entities:[] }, "data2":{ entities:[ { name:"mainData": //entites }, { name:"mainData": //entites }, { name:"m ...

What is the best way to send a POST request using axios with both body and form data included at the

Is there a way to successfully send a post request using Axios that includes both body data and form data? I am having trouble getting the data to reach my route handler: axios({ method: 'POST', url: `${keys.SERVER_URL}/post/new-post/${i ...

Creating a Scroll Bar with HTML and CSS

Recently, I've been working on creating a slider using HTML and CSS, but I've encountered an issue where the second slide displays the third image. Additionally, whenever I click on the third slide, it quickly jumps to the end of the slider. Desp ...

Issue with Argument Validation in Internet Explorer 11 while using Vue.js

Encountering an error in IE11 while the code works fine in Chrome, Mozilla, and Safari. The issue arises when trying to remove a car from the garage. The error message "Invalid Argument" pops up once I attempt to remove a car from the garage section withi ...

Is there a specific method that can be implemented in Node.js to compare two strings and identify the common words or letters?

Looking for a solution: var str1="CodingIsFun"; var str2="ProgrammingRocks"; Is there any function that can provide a true value or flag in this case? ...

What is the method for obtaining the image alt attribute using JavaScript?

I can't seem to retrieve the image alt tag using JavaScript. Is it even possible and if so, how should I go about it? Perhaps something like this: $caption.text( flkty.selectedElement ).attr('alt') (last line of JavaScript) But I'm st ...