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

142
Visualizações
AJAX requests from a React component

I am having a react component that looks something like this. It internally uses highcharts-react to render a chart by fetching a data from an API by supplying the API some of its state properties.

export default class CandlestickChart extends React.Component {
    constructor (props) {
        super(props);
        this.state = { 
            apiParam1: this.props.propData.param1,
            apiParam2: this.props.propData.param2,
            chartConfig: this.getChartConfig(this.props.apiParam1),
        };
    }

    componentDidMount() {
        this.renderChart();
    }

    render() {
        return (
            <div className='col-lg-6'>
                <div className='well'>
                    <ReactHighStock config={this.state.chartConfig} />
                </div>
            </div>
        );
    }

    renderChart() {
        var that = this;
        NanoAjax.ajax({
            url: 'myApi.com?param1=' + this.state.apiParam1 + '&param2=' + this.state.apiParam2;
        }, function (statusCode, responseText) {
            //transform the data a bit

            var chartConfig = that.getChartConfig(that.state.apiParam1);
            chartConfig.series[0].data = chartData;

            that.setState({
                chartConfig: chartConfig
            })
        });
    }

    getChartConfig(param1) {
        // returns HighCharts chartConfig object based on apiParam1
    }
}

This works perfectly fine as long as the component is static, i.e., once the params are set during initial render, the parent control will never update it. Also, this approach is same as given in here : https://daveceddia.com/ajax-requests-in-react/

However, my requirement is that, the parent control can update the props param1 and param2 of this control, causing it to make a fresh ajax call with these values and re-render the chart with new data.

How to approach this?

over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

Your solutions renders the chart only when the component has been mounted

componentDidMount() {
  this.renderChart();
}

While the requirement is to rerender the chart once param1 and param2 change. For that we could use componentWillReceiveProps, where you'll compare values and act accordingly

componentWillReceiveProps(nextProps) {
  let shouldRerenderChart = false;

  shouldRerenderChart = shouldRerenderChart || this.props.propData.param1 !== nextProps.propData.param1;

  shouldRerenderChart = shouldRerenderChart || this.props.propData.param2 !== nextProps.propData.param2;

  if (shouldRerenderChart) { 
    this.renderChart();
  }
}

Also, keep your componentDidMount function, because

React doesn't call componentWillReceiveProps with initial props during mounting.


As an alternative you could use componentDidUpdate with a similar approach.

over 4 years ago · Santiago Trujillo 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