Reputation: 329
Using this as a reference, react.js - show a message on and after form submission, I am trying to replicate something similar, but I am encountering an error in console, "Uncaught TypeError: Cannot read property 'setState' of undefined". I am unable to pinpoint where I losing the reference of 'this' in my state component.
import React from 'react'
import RadarInput from './radarInput'
class RadarForm extends React.Component {
constructor(props) {
super(props);
}
onFormSubmit = (data, cb) => {
cb(data);
}
render() {
return (
<div>
<RadarInput OnRadarSubmit={this.onFormSubmit.bind(this)} />
</div>
)
}
}
export default RadarForm
import React from 'react'
class RadarInput extends React.Component {
constructor(props) {
super(props);
this.state = {value:"Hello!", message: ''}
}
handleChange = (evt) => {
this.setState({value: evt.target.value });
}
sendContent = function(e) {
console.log("I'm in content")
console.log("this is e: ", this.state.value);
e.preventDefault();
var radarNum = this.state.value
this.setState({value: '', message: 'Please wait ...'});
this.props.OnRadarSubmit({
value: radarNum
}, function(data){
console.log("data in cb ", data.value);
this.setState({ message: data.value });
});
}
render() {
return (
<div>
Title: <div>{this.state.message}</div>
<form onSubmit={this.sendContent.bind(this)}>
Radar Number: <input type="text" value={this.state.value} onChange={this.handleChange.bind(this)} />
<input type="submit" value="Submit" />
</form>
</div>
)
}
}
export default RadarInput
Upvotes: 1
Views: 2163
Reputation: 5119
You need to set this
to a variable outside of your OnRadarSubmit()
callback first.
var self = this;
this.props.OnRadarSubmit({ value: radarNum}, function(data){
console.log("data in cb ", data.value);
self.setState({ message: data.value });
});
The reason being that in the callback, this
does not refer to the class scope any longer, so by setting self
, you are explicitly using the enclosing scope.
Upvotes: 2