In my App component I call checkUserAuth() method in order check if user is logged in or not and render different content according to this. It works fine when I call it via componentDidMount() method however it doesn't work If I try to call it via another method:
TypeError: this.checkUserAuth is not a function
In my code:
class App extends React.Component {
constructor() {
super();
this.state = {
loggedIn: false
};
this.checkUserAuth = this.checkUserAuth.bind(this);
}
componentDidMount(){
this.checkUserAuth(); // here this method can be called
}
checkUserAuth(){
const loggedUser = AuthService.isAuthenticated();
if(loggedUser){
store.dispatch(actions.loginSuccess());
this.setState({loggedIn: true});
}
}
logoutUser(){
store.dispatch(actions.logout());
this.checkUserAuth(); // here it return errors
}
How can I fix it?
thisbeing the class instance whereas your method is most likely called likethis.logoutUser()meaning inside your function,thiswill refer to the function itself. That is why you have to bind your function but notcomponentDidMountin order for it to work. This answer explains in more detail.