0

I'm unable to update filterTimeframe in Parent state. It is changing the filterDate fine. I havent included the code, but datePickerApply grabs value from a DatePicker library. The second, setTimeframe is an onChange from a select drop down. Both are in the child component.

Update: I copypasted the wrong code for Parent.

class Child extends React.Component {
    
    constructor(props) {
      super(props);
      this.state = null;
      this.datePickerApply = this.datePickerApply.bind(this);
      this.setTimeframe = this.setTimeframe.bind(this);
    }

    datePickerApply(event, picker) {

      if (typeof this.props.setDate === 'function') {
        this.props.setDate(picker.startDate.format('YYYY-MM-DD'));
      }

    }
    
    setTimeframe(event) {

      if (typeof this.props.setTimeframe === 'function') {
        this.props.setTimeframe(event.target.value);
      }

    }

 }
    
class Parent extends React.Component {

    constructor(props) {
      super(props);
      this.state = {
        filterDate: [],
        filterTimeframe: [],
      }

    }

    setDate = (filterDate) => {
      this.setState((state) => {
        return {filterDate: filterDate}
      });
      console.log(this.state.filterDate)
    }

    setTimeframe = (filterTimeframe) => {
      this.setState((state) => {
        return {filterTimeframe: filterTimeframe}
      });
      console.log(this.state.filterTimeframe)
    }

    render() {
      return (
        <div className="container">
          <div className="container-fluid" id="main-header">
            <Child filterDate={this.state.filterDate} filterTimeframe={this.state.filterTimeframe} setDate={this.setDate} setTimeframe={this.setTimeframe}}  />
          </div>
        </div>
      );
    }

}
madphp
  • 1,716
  • 5
  • 31
  • 72

1 Answers1

0

You put console.log at the wrong position. setState function is async. Read more at: https://stackoverflow.com/a/40408976/11285186

setDate = (filterDate) => {
  this.setState((state) => {
    return {filterDate: filterDate}
  }, () => {
    console.log(this.state.filterDate);
  });
}

setTimeframe = (filterTimeframe) => {
  this.setState((state) => {
    return {filterTimeframe: filterTimeframe}
  }), () => {
    console.log(this.state.filterTimeframe);
  });
}
namth
  • 2,747
  • 1
  • 9
  • 17