I am trying to call a function from another function in my React app. But I keep this error: Error in login TypeError: Cannot read property 'loadDashboard' of undefined. I searched for similar cases all I could find was (1) That I have to use this keyword (2) I have to mention the function inside constructor. I have done both then why I keep getting the error??
My code:
import React, { Component } from 'react';
import '../App.css';
var axios = require('axios');
class Login extends Component {
constructor(){
super();
this.loadDashboard = this.loadDashboard.bind(this);
}
loadDashboard(token){
axios({
method:'get',
url:'http://localhost:3000/api/dashboard',
data: {
Authorization: token
},
responseType:'stream'
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log("Error in loading Dashboard "+error);
});
}
handleOnSubmit = () => {
console.log("submittwed");
axios({
method:'post',
url:'http://localhost:3000/authenticate',
data: {
email: '[email protected]',
password: 'apple'
},
})
.then(function (response) {
var token = response.data.auth_token;
console.log(token);
this.loadDashboard(token);
})
.catch(function (error) {
console.log("Error in login "+error);
});
}
render() {
return (
<div>
Username: <input type="email" name="fname" /><br />
Password: <input type="password" name="lname" /><br />
<button onClick={this.handleOnSubmit}>LOG IN</button>
</div>
);
}
}
export default Login;
NOTE: Without loadDashboard, handleOnSubmit function works just fine.
Also, why changing loadDashboard(token){..} to function loadDashboard(token){..} gives me Unexpected token error?
this.loadDashboard = this.loadDashboard.bind(this);tothis.loadDashboard = loadDashboard.bind(this);foo() {}syntax is the shorthand forfoo: function() {}therefor you don't have to use thefunctionkeyword in classes'loadDashboard' is not defined no-undefin compilation. And the program halts.handleOnSubmit () {}and in the constructor simliar to the laodDashboard:this.handleOnSubmit = this.handleOnSubmit.bind(this)