Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Axios in VueJS - this undefined

Using typescript and vuejs + axios, i have the following .catch function on a post request - I'm attempting to trap some network errors and report status to the end user:

      .catch(function(error) {
          console.error(error.response);
          if ( error.message === "Network Error" ) {
              this.alert.show = 1;
              this.alert.message = error.message + ': Please try again later';
          }
      });

this.alert.show throws "this" undefined in the debugger. Is this a problem with javascript/typescript and exception handlers in general, or is this a bug in Axios or a design decision I can't find documentation for?

And is there a way for me to communicate this back to my component absent a "this" reference?

Full block:

export default {
  data() {
    return {
      form: {
        email: '',
        password: '',
      },
      alert: {
          show: 0,
          message: '',
      },
    };
  },
  methods: {
    onSubmit(evt) {
      evt.preventDefault();

      if (this.form.password.length > 0) {
          // TODO: Hideous workaround for .catch().
          let that = this;
          this.$http.post('http://localhost:3000/login', {
              email: this.form.email,
              password: this.form.password,
          })
          .then((response) => {
              const is_admin = response.data.user.is_admin;
              localStorage.setItem('user', JSON.stringify(response.data.user));
              localStorage.setItem('jwt', response.data.token);

              if (localStorage.getItem('jwt') != null) {
                  this.$emit('loggedIn');
                  if (this.$route.params.nextUrl != null) {
                      this.$router.push(this.$route.params.nextUrl);
                  } else {
                      if (is_admin === 1) {
                          this.$router.push('admin');
                      } else {
                          this.$router.push('dashboard');
                      }
                  }
              }

          })
          .catch((error) => {
                console.error(error);
                if ( error.message === 'Network Error' ) {
                    this.alert.show = 10;
                    this.alert.message = error.message + ': Please try again later';
                }
          });
      }
    },
    onReset(evt) {
      evt.preventDefault();
      /* Reset our form values */
      this.form.email = '';
      this.form.password = '';
      /* Trick to reset/clear native browser form validation state */
      this.show = false;
      this.$nextTick(() => { this.show = true; });
    },
  },
};

Vue template (Login.vue):

<template>
<div>
<b-container class="loginPage">
  <b-row>
    <b-col sm="4"/>
    <b-col sm="4">
      <b-form @submit="onSubmit" @reset="onReset">
         <h2>Login</h2>
         <p>Please enter your email and password</p>
         <b-form-input id="exampleInput1"
                      type="email"
                      v-model="form.email"
                      required
                      placeholder="Enter email">
         </b-form-input>
         <b-form-input id="exampleInput2"
                      type="password"
                      v-model="form.password"
                      required
                      placeholder="Enter password">
         </b-form-input>
      </b-form-group>

        <div class="forgot">
        <a href="reset.html">Forgot password?</a>
        </div>

      <b-button class="btn-primary" type="submit" variant="primary">Submit</b-button>
      <b-button class="btn-reset"   type="reset" variant="danger">Reset</b-button>

      <b-alert :show="alert.show" variant="danger">
         {{alert.message}}
      </b-alert>
    </b-form>

    </b-col>
    <b-col sm="4"/>
  </b-row>
</b-container >


    </div>
</template>

Also using https://bootstrap-vue.js.org.

like image 293
Chris K Avatar asked Dec 06 '18 18:12

Chris K


2 Answers

You're creating a new local function scope. Use fat arrow instead.

.catch((error) => {
      console.error(error.response);
      if ( error.message === "Network Error" ) {
          this.alert.show = 1;
          this.alert.message = error.message + ': Please try again later';
      }
  });
like image 132
Phix Avatar answered Oct 08 '22 05:10

Phix


You could also assign this to a global variable and access it inside callback :

    let that =this;
    ...
    .catch((error) => {
  console.error(error.response);
  if ( error.message === "Network Error" ) {
      that.alert.show = 1;
      that.alert.message = error.message + ': Please try again later';
  }
  });
like image 42
Boussadjra Brahim Avatar answered Oct 08 '22 06:10

Boussadjra Brahim