0

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?

2
  • 2
    how you are calling the logoutUser method. Commented Nov 18, 2019 at 16:22
  • Lifecycle methods are always called with the context of this being the class instance whereas your method is most likely called like this.logoutUser() meaning inside your function, this will refer to the function itself. That is why you have to bind your function but not componentDidMount in order for it to work. This answer explains in more detail. Commented Nov 18, 2019 at 16:42

1 Answer 1

3

put this in the constructor:

this.logoutUser = this.logoutUser.bind(this);

Also, consider using an auto-binding library if you find it tedious to always bind stuff. I use react-autobind

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.