Reputation: 9750
I'm getting error "Cannot read property 'props' of undefined" in ReactJS. I want to route the page to another page after login and also pass the user token for the session till logout for my app. My code :
...
import { withRouter } from 'react-router';
import { EventList } from "../EventList/EventList";
export class SignIn extends React.Component {
constructor(props) {
super(props);
this.state = {
fields: {
username: '',
password: ''
},
errors: {}
}
this.onSubmit = this.onSubmit.bind(this);
}
...
onSubmit(e){
e.preventDefault();
if(this.handleValidation()){
var apiBaseUrl = "http://api.eventsacross-stage.railsfactory.com/api/";
var input = this.state.fields;
axios.post(apiBaseUrl+'v1/users/signin', input)
.then(function (response) {
console.log(response);
if(response.data.status == 200){
console.log("Login successful");
alert("Login successful");
this.props.router.push('/EventList');
}
else if(...
}
})...
});
}
}
...
render() {
return (
...
<button type="submit" className="btn btn-primary btn-lg pull-right" onClick={this.onSubmit}>Sign In</button>
...
);
}
}
export default withRouter(SignIn);
Upvotes: 1
Views: 1461
Reputation: 1721
As it has been pointed out by @astorga, you have wrong context for 'this'. But I would recommend using Arrow Function instead of storing 'that' variable.
onSubmit(e) {
e.preventDefault();
if(this.handleValidation()){
var apiBaseUrl = "http://api.eventsacross-stage.railsfactory.com/api/";
var input = this.state.fields;
axios.post(apiBaseUrl+'v1/users/signin', input)
.then((response) => { // Arrow function here, which doesn't create new 'this' scope
if(response.data.status == 200) {
this.props.router.push('/EventList');
}
else if(...
}
});
}
}
}
Upvotes: 3
Reputation: 1601
this
inside then
function has a value different than this
of onSubmit
function.
You can read more about this
behaviour over here: this|MDN
For this to work, you should store correct this
value in another variable, just like @thomas-lin said:
onSubmit(e){
var that = this;
// ...
// later, on axios call:
axios.post(apiBaseUrl+'v1/users/signin', input)
.then(function (response) {
console.log(response);
if(response.data.status == 200){
console.log("Login successful");
alert("Login successful");
that.props.router.push('/EventList');
}
else if(...) {
//...
}
})
Upvotes: 1
Reputation: 440
It is the wrong use of "this" that lead to this mistake,try the code like this:
onSubmit(e){
var that = this
.....
that.props.router.push('/EventList');
}
Upvotes: 1