Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

155
Visualizações
React Javascript APi data not populating an array before rendering

I try to render a lineChart component in a page. I can get the data in the main page not shown here, but when I try to get the api data in the component the array is returned empty. my code is as below:

I am new to Javascript so am wondering if I am doing this in the wrong order?

import React from 'react';
import NVD3Chart from 'react-nvd3';

function getDatum() {

    const alpha = require('api')({ key: 'xxxxxxxxxxxxxxx' });
    
    var array = [];
    var newArray = [];
    alpha.data.intraday(`msft`).then((data) => {
        const polished = alpha.util.polish(data);
        {Object.keys(polished.data).map((key) => (
            array.push(polished.data[key].open)
            ))}
      });
      for (let index = 0; index < array.length; index++) {
          const element = array[index];
          newArray.push({
            'x': index,
            'y': parseFloat(element)
          })
          
      }
      
    return [
        {
            values: newArray,
            key: 'OpenPrice',
            color: '#A389D4'
        }
    ];
}



class LineChart extends React.Component {

    static data;

    constructor(props) {
        super(props);

        this.state = {
            DataisLoaded: false,
        };
    }

    componentDidMount() {
        const { DataisLoaded } = this.state;
      this.setState({
        DataisLoaded: true
    });
    LineChart.data = getDatum();
       
    }  

    render() {
        const { DataisLoaded } = this.state;
        if (!DataisLoaded) return <div>
        <h1> Please wait some time.... </h1> </div> ;
        console.log(LineChart.data)
        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: LineChart.data,
                        x: 'x',
                        y: 'y',
                        height: 300,
                        renderEnd: function(){
                            console.log('renderEnd');
                        }
                    })
                }
            </div>
        )
    }
}

export default LineChart;

I need to be able to work with this data so any help would be greatly appreciated.

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

I think what's going on is that in getDatum function the the return statement is being run before the .then() promise is being resolved. Also, typically any data that you want to render in a component is stored in the react state.

Try something like this:

import React from 'react';
import NVD3Chart from 'react-nvd3';

function getDatum(setState, lineChart) {

    const alpha = require('api')({ key: 'xxxxxxxxxxxxxxx' });
    
    var array = [];
    var newArray = [];
    alpha.data.intraday(`msft`).then((data) => {
        const polished = alpha.util.polish(data);
        {Object.keys(polished.data).map((key) => (
            array.push(polished.data[key].open)
            ))}
    for (let index = 0; index < array.length; index++) {
          const element = array[index];
          newArray.push({
            'x': index,
            'y': parseFloat(element)
          })
          
      }
// If you need data from the previous state one way to do it is to merge in lineChart with this state, but I'm not sure where you'd do it because I'm not sure where .data is coming from.
setState([
        {
            values: newArray,
            key: 'OpenPrice',
            color: '#A389D4'
        }
    ])
      });
      
}



class LineChart extends React.Component {

    static data;

    constructor(props) {
        super(props);

        this.state = {
            DataisLoaded: false,
            lineChart: []

        };
    }

    componentDidMount() {
        const { DataisLoaded, lineChart } = this.state;
    getDatum(this.setState, lineChart);
this.setState({
        DataisLoaded: true
    });
       
    }  

    render() {
        const { DataisLoaded, lineChart } = this.state;
        if (!DataisLoaded) return <div>
        <h1> Please wait some time.... </h1> </div> ;
        console.log(LineChart.data)
        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: lineChart.data, // I don't really know where .data is coming from??
                        x: 'x',
                        y: 'y',
                        height: 300,
                        renderEnd: function(){
                            console.log('renderEnd');
                        }
                    })
                }
            </div>
        )
    }
}

export default LineChart;
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda