I cannot get my data to populate my line chart. The data from the API call comes back fine but when I try to pass that data into the chart it is of length 0. So I assume there is some issue with the response got being called at the right time? But I have tried so many times to sort this and nothing ever works?
import React from 'react';
import NVD3Chart from 'react-nvd3';
import SamplePage from './SamplePage';
function getData(){
const alpha = require('account')({ key: 'xxxxxxxxxxxx' });
var array = [];
alpha.data.intraday(`msft`).then((data) => {
const polished = alpha.util.polish(data);
{Object.keys(polished.data).map((key) => (
array.push(polished.data[key].open)
))}
});
return array;
}
function getDatum() {
let dataArray = getData();
let newArray = [];
for (let index = 0; index < dataArray.length; index++) {
const element = dataArray[index];
newArray.push({
'x': index,
'y': parseFloat(element)
})
}
return [
{
data: newArray,
key: 'OpenPrice',
color: '#A389D4'
}
];
}
class LineChart extends React.Component {
constructor(props) {
super(props);
this.state = {
DataisLoaded: false,
data:[]
};
}
componentDidMount() {
this.state.data = getDatum();
this.setState(
{
DataisLoaded: true,
data: this.state.data
}
)
}
render() {
const { DataisLoaded } = this.state;
if (!DataisLoaded) return <div>
<h1> Please wait.... </h1> </div>;
return (
<div>
{
React.createElement(NVD3Chart, {
xAxis: {
tickFormat: function(d){ return d; },
axisLabel: 'Time (ms)'
},
yAxis: {
axisLabel: 'Voltage (v)',
tickFormat: function(d) {return parseFloat(d).toFixed(2); }
},
type:'lineChart',
datum: this.state.data,
x: 'x',
y: 'y',
height: 300,
renderEnd: function(){
console.log('renderEnd');
}
})
}
</div>
)
}
}
export default LineChart;