I would like to update the state of a component when a date is selected from the React-DatePicker. I am getting some odd behavior below.
Example of Current Behavior:
- Component loads with empty date field
I select 3/28/2017 and get the following console log
main.ffde8a1f.js:8 it changed dates
main.ffde8a1f.js:8 date = 1490673600000
main.ffde8a1f.js:8 dueDate value =
Say then I select 3/22/2017 and get the following console log:
main.ffde8a1f.js:8 it changed dates
main.ffde8a1f.js:8 date = 1490155200000
main.ffde8a1f.js:8 dueDate value = 1490673600000
The second and third logs should have the same value. Can anyone explain to me why this weird behavior is occurring?
MY ATTEMPT
Imports
import React from 'react';
import DatePicker from 'react-datepicker';
import moment from 'moment';
import 'react-datepicker/dist/react-datepicker.css';
Component
I set the state of dueDate
to ''
to begin.
export default class Request extends React.Component {
constructor(props) {
super(props);
this.state = {
dueDate: '',
}
this.handleChangeDate = this.handleChangeDate.bind(this);
}
Handle Date Selection
ISSUE
My handleChangeDate
function will fire when a date is provided and the date in milliseconds will log to the console, but the dueDate is logged as being the previous value it should have been.
handleChangeDate(date) {
console.log("it changed dates");
console.log('date = ' + date); //date in milliseconds logs properly
this.setState({
dueDate: date
});
console.log('dueDate value = ' + this.state.dueDate); //date from state logs the previous value rather than its new value
}
Render
I am keeping the date picker simple at the moment to minimize potential bugs. Only the selected date is passed in from the state and the handleChangeDate
method for a selected date.
render() {
return (
<div className="requestDetails">
<h2>Due Date</h2>
<DatePicker
selected={this.state.dueDate}
onChange={this.handleChangeDate}
/>
</div>
);
}
}