1

I am a little confused as to why this function of mine will not update the state like it should. I get a date object, then convert it to the format I would like it in, but when I try and set the state at the very bottom, the callback alert is just blank.

How can I make it so the state updates as soon as this function is over?

floorLastCleanedChange(date) {
    this.setState({ flooringLastCleanedTest: date });
    var floorDate = new Date(date);
    alert(floorDate);
    var day = floorDate.getDate();
    if(day.toString().length === 1)
    {
        day = '0' + day;
    }
    var month = floorDate.getMonth() + 1;
    if(month.toString().length === 1)
    {
        month = '0' + month;
    }
    var year = floorDate.getFullYear();
    alert(month+"/"+day+"/"+year);
    this.setState({flooringLastCleaned: month+"/"+day+"/"+year}, alert(this.state.flooringLastCleaned));
}
0

1 Answer 1

4

Try this. The callback to setState is only a function, you were making a function call instead in your code in the callback.

setState(
  {flooringLastCleaned: month+"/"+day+"/"+year},
  () => alert(this.state.flooringLastCleaned);
);
2
  • Well that did the trick! I guess I didn't quite understand what the callback needed exactly. Thank you very much!! Commented Jul 22, 2018 at 13:49
  • 1
    @PushedCrayon Good answer. regarding your comment, you need to pass a function definition as a callback without calling it, which is later called (when the state is updated). In your code you were calling alert right away, instead of passing it. Commented Jul 22, 2018 at 13:53

Not the answer you're looking for? Browse other questions tagged or ask your own question.