I think this is due to setState() being asynchronous
You are completely right.
before checkUrl
finishes setState
the code below has already been executed:
const { errorMessage } = this.state;
if (this.state.error) {
this.setState({
helperText: errorMessage
});
}
Fix:
handleSubmit = e => {
e.preventDefault();
const { url } = this.state;
const error = this.checkUrl(url);
if(error) {
this.setState({
helperText: error,
errorMessage: error,
error: true,
});
}
};
checkUrl = url => {
if (!validUrl.isWebUri(url)) {
return "please enter a valid url";
}
return null;
};
You probably aren't gonna need both errorMessage
and helperText
in the state.
EDIT:
Because setState
is asynchronous you would have to use setState
callbacks to avoid errors like:
handleSubmit = e => {
e.preventDefault();
const { url } = this.state;
if (!validUrl.isWebUri(url)) {
this.setState({ error: true, errorMessage: "please enter a valid url" }, () => {
// ... this callback is fired when react has updated the state
const { errorMessage } = this.state;
if (this.state.error) {
this.setState({
helperText: errorMessage
});
}
});
}
};
but this is just overcomplicating.