When working with typescript and vuejs + axios, I have included the following .catch function on a post request to handle network errors and inform the user of the status:
.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';
}
});
The issue arises when this.alert.show throws an error stating that "this" is undefined in the debugger. Is this a common problem with javascript/typescript and exception handlers, or could it be a potential bug in Axios or possibly a design decision lacking documentation?
Is there a method to communicate this back to my component without using a "this" reference?
Here is the full section of code:
export default {
data() {
return {
form: {
email: '',
password: '',
},
alert: {
show: 0,
message: '',
},
};
},
methods: {
onSubmit(evt) {
evt.preventDefault();
if (this.form.password.length > 0) {
// Workaround for handling .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>
This project also utilizes .