Leveraging Axios within VueJS - the missing piece

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 .

Answer №1

When establishing a new local function scope, consider utilizing the fat arrow syntax for improved clarity.

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

Answer №2

One option is to store this in a global variable and use it within the callback function:

    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';
  }
  });

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Directive ng-click not executing as expected

Currently, I am developing an Angular application that involves a controller named visualization and a directive named force-layout. Within the HTML template of the directive, I have implemented three buttons with corresponding functions attached to them. ...

Generating JSON data on the fly using D3.js scripting

I am attempting to create a JSON object dynamically by pulling data from an array in D3 JavaScript. (The code below is not the exact one I used, but similar) let radius = [10,20,30]; let jsonradius = '[{'; for (let i = 0; i < radius.le ...

How to load images in TreePanel in Ext JS

While creating an Ext.TreePanel, I wanted to include an image in the node along with the text containing the URL to the image. However, I encountered an issue where the image was not loading on the page, only the text was visible. Is there a way to display ...

Leveraging the find method to sort through an array with dual parameters

I'm facing an issue while trying to filter my array of objects using two parameters. Despite having an object in the array with the same values as the parameters, the result is empty. const item = this.lista.find(i => i.number === rule.number && ...

What causes getServersideprops to return undefined?

The data I am trying to fetch is showing as undefined in the console. Here is the code snippet: export default function Home({ data }) { console.log(data); return ( <div> <h2>Welcome !!</h2> </div> ); } export a ...

There appears to be an issue with the addrow() function in JavaScript

function addNewRow() { var medication = document.getElementById("medicinename"); var timeOfDay = document.getElementById("time"); var treatmentDuration = document.getElementById("duration"); var timing = document.getElementById("when"); ...

Updating the parent page host within a cross-domain iframe: issues encountered in Firefox and Chrome browsers

I am encountering an issue with my iframe app where I am receiving an alert indicating "-error" in Chrome related to top.location.href. jQuery.ajax({ type : 'get', url : 'check_if_fb_data_set.php', success ...

What causes the repeated submission of PHP form when I refresh the page?

Every time I submit my form and press ctrl-r, the page refreshes without warning me that it will resubmit the form. Similarly, clicking the reload button on the browser results in a prompt to reload, even though the form has already been submitted. Consequ ...

"Combining background images with javascript can result in displaying visual elements

Hello! I am in need of assistance with a CSS + Javascript fog effect that I have developed. It is functioning properly on Firefox, Opera, and Chrome but encountering issues on IE and Edge browsers. The effect involves moving two background images within a ...

Removing all items with a specific ID and its related items in Javascript: How to achieve this recursively?

I am currently facing some challenges in figuring out the most effective approach for this scenario. For example, consider the data structure below: const arr = [{ parentId: 1, children: [ { childId: 11 }, { childId: 21 }, { childId: 31 }, ...

The PhotoService (?) is facing difficulties in resolving dependencies according to Nest

Just started diving into Nest.js and encountering an issue right after setting up a service: Nest is throwing an error while trying to resolve dependencies of the PhotoService (?). Make sure that [0] argument is accessible in the current context. I' ...

Tips for adding elements to an angular $scope.array?

Currently, I am facing an issue that I cannot seem to pinpoint (most likely due to my limited expertise in AngularJS). In my HTML file, I have a basic ng-repeat set up like this: <ul> <li ng-repeat="fot in fotografia"><img src="{{fot.path ...

Prevent side menu from automatically hiding when clicking on the heading

My menu is set up with headings and subheadings. When I click on the headings, it expands to display the corresponding subheadings, but it automatically collapses when clicking on the headings. I want it to stay expanded when clicking on the headings. He ...

Unable to send a POST request to http://localhost:5000/api/createuser

During my journey through a MERN stack project tutorial on YouTube, I've come across a roadblock in the middle of my progress. The issue at hand involves the incorporation of user registration, which is a recent addition to my project. Utilizing Thund ...

Steps to assign the user id where the isDisliked field is not true

I'm struggling to populate the user from the likedBy field where isDisliked is false. Can you please refer to the document schema https://i.sstatic.net/jb8x8.png for more information? Although I've tried using the query below, I can't seem ...

Unable to invoke JS function in Drupal 5 file

In my current project using Drupal 5, I have a specific .js file that is included using the code: drupal_add_js(drupal_get_path('module','MTM')."/include/JS_form.js"); Additionally, there is an element on the page: <a onclick="MTM ...

Executing a jQuery function automatically & Invoking a jQuery function using the onClick attribute in an HTML element

Having some issues with jQuery and could use some assistance... Currently, I am trying to have a jQuery function automatically execute when the page loads, as well as when a button is clicked. [Previous Issue] Previously, the jQuery function would automa ...

Creating an attractive image carousel using jQuery or YUI for your website

I am searching for a javascript-based slideshow solution for images. I have received the following requirements: The slideshow should fade one image into another, looping back to the first image after all images have been displayed It must include naviga ...

Two buttons next to each other positioned below my magnified picture

I'm currently working on implementing a feature where clicking an image enlarges it and displays two buttons at the bottom, but I'm facing some challenges with getting the buttons to show up. Any assistance would be greatly appreciated! Addition ...

What are the best methods for exchanging code among different TypeScript projects?

Imagine having two separate projects, each with its own unique file structure: /my-projects/ /project-a/ lib.ts app.ts tsconfig.json /project-b/ app.ts // import '../project-a/lib.ts' tsconfig.json How can I ac ...