Reputation:
There are many similar questions, though I am posted it here.
I am getting the following error:
Uncaught Invariant Violation: Maximum update depth exceeded. This can happen when a component repeatedly calls setState inside componentWillUpdate or componentDidUpdate. React limits the number of nested updates to prevent infinite loops.
Please note that I haven't used such functions in page.
Error occurred while selecting Datepicker
:
constructor(props){
super(props);
this.state={
fields: {},
errors: {}
}
}
handleIssueDate(date){
// this.state.IssueDate = moment(date).format("YYYY-MM-DD")
debugger;
let fields = this.state.fields;
fields["IssueDate"] = moment(date).format("YYYY-MM-DD")
this.setState({
fields
});
let errors = this.state.errors;
if (errors[date] != "" || errors[date] != null) {
errors["IssueDate"] = "";
}
}
render(){
return (
<DatePicker name="IssueDate" onChange={this.handleIssueDate} selected={this.state.fields.IssueDate} value={this.state.fields.IssueDate} placeholderText={"YYYY-MM-DD"} />)
}
EDITED : I just removed moment function from setState. now its working fine. Please any one explain this weird error/behavior.
Upvotes: 0
Views: 961
Reputation: 1
https://github.com/Hacker0x01/react-datepicker/blob/master/docs/datepicker.md
selected type is instanceOf(Date) not a string
Upvotes: 0
Reputation: 41893
Apparently you are mutating the state.
let fields = this.state.fields; // fields still holds the reference to the state
fields["IssueDate"] = moment(date).format("YYYY-MM-DD") // here happens the mutation
this.setState({ // state is changed again
fields,
});
errors["IssueDate"] = ""; // state mutation once again
Suggested approach:
define the 'IssueDate' field inside state:
state = {
fields: {
IssueDate: null,
},
error: {
IssueDate: null,
},
}
and then inside your onChange func:
this.setState(({ fields }) => ({
fields: {
...fields,
IssueDate: moment(date).format("YYYY-MM-DD"),
},
});
Do likewise with error.
Upvotes: 1