Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

149
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda