Reputation: 282
I have a problem with my react app. I have form with 2 components (two separate pickers), and I need to change component state when the date is incorrect. Here is the code:
constructor(props: EditFormProps) {
super(props);
this.state = {
isValidDate: true,
isValidTime: true
} as EditFormState;
this.validateDate = this.validateDate.bind(this);
this.validateTime = this.validateTime.bind(this);
}
render() {
return (
<div>
<FormSection title={FLIGHT_DATES} className="flight-dates">
<div>
<DateRange validateDate={this.validateDate} />
</div>
<div>
<TimeOfDate validateTime={this.validateTime} />
</div>
</FormSection>
</div>
);
}
}
private validateDate(isValidDate: boolean) {
this.setState({
...this.state,
isValidDate: isValidDate,
} as EditFormState);
}
private validateTime(isValidTime: boolean) {
this.setState({
...this.state,
isValidTime: isValidTime,
} as EditFormState);
}
When I have only one function like validateDate its set state for isValidDate without problem, but when i have 2 functions (validateDate and validateTime) i got proper parameter for validateDate but state is always the same (it's working fine for isValidTime). When I change positions in FormSection and TimeOfDate is 1st I have same problem for isValidTime state and isValidDate it woks good. So probably I have some bigger problem in my project, but maybe there is other way to set this state or pass parameter from DateRange or TimeOfDay?
Upvotes: 1
Views: 338
Reputation: 12727
Please, try to remove ...this.state
from the validation functions
Maybe you call both validation function in the same time-frame? React merges multiple setState functions into one, so it is possible that you have something like this:
set newIsValidDate => set newIsValidTime and setOldIsValidTime
Upvotes: 2
Reputation: 1342
I think that the problem with your code is that you are reading from this.state
inside the this.setState()
call.
In this case this.state
is not guaranteed to contain the up-to-date state.
You should pass a function to this.setState()
rather than an object. E.g:
private validateDate(isValidDate: boolean) {
this.setState((prevState, props) => ({
...prevState,
isValidDate: isValidDate
})
}
More info in the react docs .
Upvotes: 2