Reputation: 123
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));
}
Upvotes: 1
Views: 82
Reputation: 1893
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);
);
Upvotes: 4