0
votes

I have a react component like this:

const students: [
  {id: '', name: '', age: '', attendance: ''}
  //... 1000 entries
]



class Students extends React.Component {

  constructor (props) {
    super(props)

    this.state = {
      studentID: 1
    }
  }



  createMonthlyChart = () => {
    const { studentID } = this.state
    let computeScore = students.attendance.map (
      item => {
        //... get attendance by id
      }
    )

    return chartData
  }

  handleOnChange = value => {
    console.log(value) // student key

    this.setState({
      studentID: value
    })

    this.createMonthlyChart() // not working
  }


  render () {
    return (
      <div>
        // ant design component
        <Select
          defaultValue={type}
          onChange={this.handleOnChange}
        >
        students.map((student, key) => (
          <Option key={student.id}> {student.name} </Option>
        ))
        </Select>
      </div>
    )
  }
}

That is the just idea

I am not sure if I am using setState wrongly but somehow I get unexpected value

For example, the first time I click on a student, I don't get any chart visualization even though the data is there, I have to press it second time to get any chart.

And If I click on student without any attendance, I get empty chart after that for all students. I have to refresh the page to restart

2
Consider passing studentID as a parameter into createMonthlyChart rather than relying on state.Soc

2 Answers

1
votes

To me it seems like you don't need the studentID state at all, you could directly call this.createMonthlyChart passing the value as a parameter to the function. But if you need it for some other reason you can invoke that function as a callback to the setState like this:

this.setState({
  studentID: value
}, this.createMonthlyChart)
1
votes

I see a couple of things

The option should have the value

<option key={student.id} value={student.id}> {student.name}</option>

createMonthlyChart, should be called after updating the state (second parameter)

And you should use event.target.value

handleOnChange = event => {
  this.setState({
    studentID: event.target.value,
  }, this.createMonthlyChart);
};

And for the first time, you can use componentDidMount

componentDidMount() {
  this.createMonthlyChart();
}

And don't forget to initialize the state with the first student, like this

this.state = {
  studentID: students[0].id,
};