'Component variable can't be modified in a callback method in vue.js

I defined a Login.vue component in the vue.js that let's me login the user to my application through AWS Cognito. I use the ___.authenticateUser() method to login the user and start a session with Cognito. Below is the actual code that does so:

export default {
  name : 'Login',
  data: function() {
    return {
      errorMessageHidden: true,
      formHidden: false,
      errorMessage: '',
      email: '',
      password: ''
    }
  },
  methods: {
    showValuesToMe: function() {
      console.log(this.errorMessageHidden)
    },
    handleLogin: function() {
      const data = {
        Username: this.email,
        Pool: userPool
      }

      const cognitoUser =  new CognitoUser(data);

      const authenticationData = {
        Username : this.email,
        Password : this.password,
      };

      function showErrorMessage(err) {
        this.errorMessageHidden = false;
        this.errorMessage = err.message;
        console.log("The method got called... errorMessageHidden = " + this.errorMessageHidden);
      }

      const authenticationDetails = new AuthenticationDetails(authenticationData)

      cognitoUser.authenticateUser(authenticationDetails, {
        callback: showErrorMessage,
        onSuccess: function(result) {
          console.log('access token ' + result.getAccessToken().getJwtToken());
        },
        onFailure: function(err) {
          this.callback(err);
        }
      });
    },

    hideErorrMessage: function() {
      this.errorMessageHidden = true;
    }
  }
}

The issue is, inside the handleLogin() function of the component, when ___.authenticateUser() is called Cognito SDK calls either onSuccess() or onFailure() depending on the auth result from the AWS.

Inside the onFailure() when I try to modify the errorMessageHidden and errorMessage they can't be! It happens because the onFailure() method is a callback method and a closure.

To access/modify these values I defined the function showErrorMessage(err) {...} in the scope of closure's parent. Now I can access the values defined in data but still can't modify them.

Can anyone figure it out how I can change the values to make changes and show error in the browser.



Solution 1:[1]

This worked for me:

Function in the this components:

BusEvent.$emit("CloseAllTab",check => {
  if(check == true){
    this.isShowSelectYearActive = true;
  }
});

Function in the other components:

methods: {
  CloseAllTab(check) {
    check(true);
  }
},
created() {
  BusEvent.$on("CloseAllTab",this.CloseAllTab);
},
beforeDestroy() {
  BusEvent.$on("CloseAllTab",this.CloseAllTab);
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Sebastiano Vierk