Home > Blockchain >  Successfully get the data from Flask but cannot render the website
Successfully get the data from Flask but cannot render the website

Time:08-04

I want to use the eCharts to draw the candletick picture. I get the data from flask using Axios:

request.post('/investor').then(res=>{
 var arr=Object.keys(res.close)
  for(let i=0;i<arr.length;i  ){
    this.stockdata[i]=[]

for(let j=0;j<4;j  ){
  var temp=[]
  temp[0]=res.open[i]
  temp[1]=res.close[i]
  temp[2]=res.low[i]
  temp[3]=res.high[i]
  this.stockdata[i][j]=temp[j]
}
  }

})

this my data:

The 2d array

1

but it cannot render the website
then i create the data using the method below(assign data manually):

this.stockdata= [
        [20, 34, 10, 38],
        [40, 35, 30, 50],
        [31, 38, 33, 44],
        [38, 15, 5, 42]
      ]

it successfully draw the picture,i don't know why.
and this my main function:

mounted(){
request.post('/investor').then(res=>{
 var arr=Object.keys(res.close)
  for(let i=0;i<arr.length;i  ){
    this.stockdata[i]=[]

for(let j=0;j<4;j  ){
  var temp=[]
  temp[0]=res.open[i]
  temp[1]=res.close[i]
  temp[2]=res.low[i]
  temp[3]=res.high[i]
  this.stockdata[i][j]=temp[j]
}
  }

})
console.log(this.stockdata)
    var echarts = require('echarts');
var option = {
  xAxis: {
    data: ['2017-10-24', '2017-10-25', '2017-10-26', '2017-10-27']
  },
  yAxis: {},
  tooltip: {
    trigger: 'axis'
  },
  series: [
    {
      type: 'candlestick',
      data:this.stockdata
    }
  ]
};
var charts = echarts.init(this.$refs.myChart);
charts.setOption(option);
   }
}

CodePudding user response:

There is not enough information, but I can still guess. I am going to assume that your Object.keys double for loop with i and j works fine. To be sure of that, please add console.log(this.stockdata) after both loops end running, to make sure you are building your data from the response the right way.

The error is probably because in your code you call the async function, which is calling your API.

// this *.then* happens after the initial render, and after a delay it gets a value,
// which is too late
request.post('/investor').then(res=>{

This causes that at the exact frame the App is being rendered, your response is not yet there, causing your App to break because this.stockdata is still undefined. One way to fix it is the following:

// in render function:
{this.stockdata && <YourComponent dataToRender={this.stockdata} />}

This will prevent rendering YourComponent until the API response is there

  • Related