Home > Software design >  React.js setState on page load not working, how to fix
React.js setState on page load not working, how to fix

Time:05-10

I am using the react-apexcharts to create a piechart. I am with success in rendering the series=[] because it is native from the component apexcharts.

But I am trying to render also the labels, which is a simple array.

If I run the console.log:

console.log(this.props.total.map(a=>a.name))

render

["label 1","label 2","label 3"]

How can update the label: [], with the values from this.props.total.map(a=>a.name)?

The full code is below

import React from 'react'
import { Card, CardHeader} from 'reactstrap'
import Chart from 'react-apexcharts'

class PieChart extends React.Component {
  constructor(props) {
    super(props);

    this.state = {    
      series: [],
      options: {
        chart: {
          width: 380,
          type: 'pie',
        },
        labels: [],
        theme: {
          mode: 'light', 
          palette: 'palette2', 
        },
        legend: {
          show: true,
          position: 'bottom',
          horizontalAlign: 'center', 
          floating: false,

      }
      
      },
    };
  }


  componentDidMount() {
    this.setState({
      label: this.props.total.map(a=>a.name),
    })
  }


  render() {
    return (
        <>

        <Card  color="gray" className="mb-3">
            <CardHeader className="bg-gray-lighter">PieChart</CardHeader>
            <Card body>
                <div id="chart3">
                  <Chart 
                  options={this.state.options} 
                  series={this.props.total.map(a=>a.total_today_brl)} 
                  type="pie" 
                  height={450} 
                  />
                </div>
                </Card>
        </Card>
        </>
    );
  }
}
export default PieChart;

I tried without success:

<Chart 
   options={this.state.options} 
   series={this.props.total.map(a=>a.total_today_brl)} 
   labels={this.props.total.map(a=>a.name)}
   type="pie" 
   height={450} 
/>

And tried also:

      options: {
        chart: {
          width: 380,
          type: 'pie',
        },
        labels: this.props.total.map(a=>a.name),
        theme: {
          mode: 'light', 
          palette: 'palette2', 
        },

CodePudding user response:

labels is under options

so in order to update the label on the state, you need to do

this.setState((prevState)=> ({
  ...prevState,
  options:{ ...prevState.options,
            labels: this.props.total.map(a=>a.name)
          }
}))
  • Related