Reputation: 143
A user clicks the button, onClick
I make an ajax post request and I'm trying to setState in my .then()
and .catch()
phases of my request. I keep getting
"Can only update a mounted or mounting component. This usually means you have called setState() on an unmounted component. This is a no-op. Please check the code for the ContactForm component."
What am I doing wrong?
const ContactForm = React.createClass({
componentDidMount() {
this._mounted = true;
},
componentWillMount() {
this._mounted = false;
},
getInitialState() {
return {
formSubmitted: false,
formSuccess: false,
}
},
submitForm(info) {
this.props.setLoading(true);
axios.post('/contact', info)
.then(response => {
this.handleSuccess(response);
})
.catch(error => {
this.handlError(error);
});
},
handleSuccess(response) {
console.log(response);
this.props.setLoading(false);
this.state.formSubmitted = true;
this.state.formSuccess = true;
if (this._mounted) {
this.setState(this.state);
}
},
handlError(error) {
console.log("error")
this.props.setLoading(false);
this.state.formSubmitted = true;
this.state.formSuccess = true;
if (this._mounted) {
this.setState(this.state);
}
console.log(error);
},
render() {
console.log(this.state);
return (
<div className="col-xs-12 col-sm-12 col-md-5 col-md-offset-1 wow fadeInUp" data-wow-delay="0.3s">
<div className="form-group">
{this.state.formSubmitted == false ? <Form submitForm={this.submitForm} /> : null}
{this.state.formSubmitted && this.state.formSuccess ? <FormSuccess /> : null}
{this.state.formSubmitted && !this.state.formSuccess ? <FormError /> : null}
</div>
</div>
)
}
})
Upvotes: 0
Views: 313
Reputation: 282030
You should not mutate the state directly.
handleSuccess(response) {
console.log(response);
this.props.setLoading(false);
if (this._mounted) {
this.setState({formSubmitted: true, formSuccess: true});
}
},
handlError(error) {
console.log("error")
this.props.setLoading(false);
if (this._mounted) {
this.setState({formSubmitted: true, formSuccess: true});
}
console.log(error);
},
Upvotes: 3