user1050619
user1050619

Reputation: 20856

trouble setting state in reactjs

I have a very simple code to set a state variable but have trouble.

https://codesandbox.io/s/highcharts-react-demo-rtlie

I see the this.state.chart_options being displayed on the console but its null.

Code:_

import React from "react";
import { render } from "react-dom";
// Import Highcharts
import Highcharts from "highcharts/highstock";
import drilldow from "highcharts/modules/drilldown";
//import HighchartsReact from "./HighchartsReact.js";
import PieChart from "highcharts-react-official";
drilldow(Highcharts);
const options = {
  chart: {
    type: "pie"
  },
  series: [
    {
      data: [{ y: 100, name: "Female" }, { y: 50, name: "Male" }]
    }
  ]
};
class App extends React.Component {
  constructor() {
    super();
    this.state = {
      chart_options: null
    };
    this.setState({ chart_options: options }, () => {
      console.log("this.state - ", this.state);
      console.log("options - ", options);
    });
  }
  onFilterClickHandler = () => {
    console.log("hi", this.state.chart_options);
  };
  render() {
    const key = 1;
    return (
      <div>
        <div>
          <label>
            <input
              type="checkbox"
              value={key}
              onClick={this.onFilterClickHandler}
            />
          </label>
        </div>
        <h2>Highcharts</h2>
        <PieChart highcharts={Highcharts} options={options} />
      </div>
    );
  }
}

render(<App />, document.getElementById("root"));

Upvotes: 0

Views: 40

Answers (1)

Juan Marco
Juan Marco

Reputation: 3241

You're calling setState inside the constructor (when the component is not yet mounted).

To get the expected console.log output, call setState from the lifecycle method componentDidMount:

class App extends React.Component {
  constructor() {
    super();
    this.state = {
      chart_options: null
    };
  }

  componentDidMount() {
    this.setState({ chart_options: options }, () => {
      console.log("this.state - ", this.state);
      console.log("options - ", options);
    });
    console.log(this.state);
  }

  onFilterClickHandler = () => {
    console.log("hi", this.state.chart_options);
  };
  render() {
    const key = 1;
    return (
      <div>
        <div>
          <label>
            <input
              type="checkbox"
              value={key}
              onClick={this.onFilterClickHandler}
            />
          </label>
        </div>
        <h2>Highcharts</h2>
        <PieChart highcharts={Highcharts} options={options} />
      </div>
    );
  }
}

Upvotes: 1

Related Questions