0

I have a react app where in the constructor I initialize my displayDate to an empty string. When the app loads, the displayDate value gets set based on the props.

constructor(props){
    this.calendar = null;
    this.state{
        displayedDate: ""
    };
}

componentDidMount(){
    this.calendar = new Calendar({
            format: "MM/DD/YYYY",
            value: this.state.displayedDate
    });
}

componentWillMount(){
    if(this.props.defaultDate){
        this.setState({
            displayedDate: this.convertDateToString(this.props.defaultDate)
        });   
    }
}
// many many more lines of code that follow this

render(){
    return(
        <input type="text"></input>
        <i class="fa fa-calendar" id="calendar"></i>
    );
}

In testing the app, I set a breakpoint on this.setState in componentWillMount and it does indeed enter the if block, so the app is receiving the date value from props. But setState doesn't seem to be setting the displayedDate to state. And my convertDateToString function returns a value, so its not an issue of displayedDate getting a void value. In componentDidMount I set a breakpoint and dumped the state value and displayedDate is still an empty string.

I've seen people experience similar issues like this before, where setState doesn't work as expected. What am I doing wrong? Thanks

danielschnoll
  • 3,045
  • 5
  • 23
  • 34
  • Does this answer your question? [Why calling setState method doesn't mutate the state immediately?](https://stackoverflow.com/questions/42593202/why-calling-setstate-method-doesnt-mutate-the-state-immediately) – Brian Thompson Apr 15 '21 at 21:23
  • why so complicated? I'd move the code from the lifecycle methods up into the constructor. – Thomas Apr 15 '21 at 21:35
  • Try displaying `${this.state}` or `console.log(this.state)` in render function. `setState()` does not apply state changes immediately(as noted by Brian). Once it's applied React will call `render` and will refresh the UI. – Vitalii Apr 15 '21 at 23:23
  • @Thomas I ran into issues with the calendar initialization in the constructor. The calendar has additional fields that are dependent on the rendering of the html elements, so I needed to use some `createRef`s. The consequence was moving the initialization to a lifecycle method so the calendar would initialize after the app loads. – danielschnoll Apr 16 '21 at 03:51

0 Answers0