Chartjs-React/Chartjs change data with a button

0👍

Looks like you initialize state to your data object but then are setting newData as a property of state instead of replacing the entire state object.

this.setState({
    //legend: opts;
    newState
  });

Change to:

this.setState(newState)
 var Labels = ["2010", "2011", "2012", "2013", "2014", "2015", "2016"];
 var Datas = [65, 59, 80, 81, 56, 55, 69];


const data = {
  labels: Labels
  datasets: [{
    data: Datas,
    backgroundColor: [
    '#FF6384',
    '#36A2EB',
    '#FFCE56'
    ],
    hoverBackgroundColor: [
    '#FF6384',
    '#36A2EB',
    '#FFCE56'
    ]
  }]
};

const legendOpts = {
  display: true,
  position: 'top',
  fullWidth: true,
  reverse: false,
  labels: {
    fontColor: 'rgb(255, 99, 132)'
  }
};

export default React.createClass({
  displayName: 'LegendExample',

  componentWillMount(){
    this.setState(data);
  },

  getInitialState() {
    return {
      legend: legendOpts,
    }
  },


  changeData() {
    const { value } = this.legendOptsInput;
    var oldDataSet = this.state.datasets[0];
    var newData = [65, 59, 80, 81, 56, 55, 69];
    var newDataSet = {
      ...oldDataSet
    };

    newDataSet.data = newData;
    console.log('this is:', newDataSet.data);

    var newState = {
      ...data,
      datasets: [newDataSet]
    };
    try {
      const opts = JSON.parse(value);
      this.setState(newState);
    } catch(e) {
      alert(e.message);
      throw Error(e);
    }
  },

  render() {
    return (
      <div>
        <h2>Example</h2>
        <textarea
          cols="40"
          rows="15"
          ref={input => { this.legendOptsInput = input; }}
          defaultValue={JSON.stringify(this.state.legend, null, 2)}></textarea>
        <div>
          <button onClick={this.changeData}>Change data!</button>
        </div>
        <Line data={this.state} legend={this.state.legend} redraw />
      </div>
    );
  }
})

Leave a comment