简体   繁体   中英

inconsistent respond from data and API using vue.js and axios

I'm trying to load data retrieved from my API using axios into vue.js data function. i've split the process to two functions, one retrieving the data from my api and assigning it to a variable and another one that should manipulate it.

unfortunately when i log the data in each function i get different results.

here is what im doing:

let sendGetRequest = async () => {
  try {
    console.log('getting');
    const res = await axios.get('/api/v1/leaderboard');
    let resData= res.data
    this.pastWinners = resData.history
    this.chart = resData.chart
    console.log('this ', this.chart)
    this.users = resData.users
  } catch (err) {
    console.error(err)
  }
};

let objectManipulation = () => {
  console.log('manipulating');
  console.log(this.chart)
}

sendGetRequest();
objectManipulation();

the first log (from sendGetRequest ) return the data as it should be:

(7) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, __ob__: Observer]

whilst the second function returns:

[__ob__: Observer]
length: 0
__ob__: Observer {value: Array(0), dep: Dep, vmCount: 0}
[[Prototype]]: Array

thanks!

Thanks to @daantje answer i was able to fix the problem.

to resolve it i called sendGetRequest from within objectManipulation using async & await , like this:

let sendGetRequest = async () => {
  try {
    console.log('getting');
    const res = await axios.get('/api/v1/leaderboard');
    let resData= res.data
    this.pastWinners = resData.history
    this.chart = resData.chart
    console.log('this ', this.chart)
    this.users = resData.users
    console.log('done')
  } catch (err) {
    console.error(err)
  }
};

let objectManipulation = async () => {
  // eslint-disable-next-line no-unused-vars
  let res = await sendGetRequest()
  console.log('manipulating');
  console.log(this.chart)
}

objectManipulation();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM