Getting a property from an axios function within the Vue 'created' method - here's how

I am trying to implement the Axios interceptors to display a loader component while Axios is making a request. The issue I am facing is related to accessing the isLoading property within the Axios function. In my root component, I have set up these interceptors in the created() function. Within this component, I have defined a property called isLoading which is initialized as false. However, when a request is triggered, I want to update it to true. But unfortunately, when I attempt to access this property, an error is thrown:

TypeError: Cannot read property isLoading of undefined

I'm puzzled by why I cannot access the isLoading property from inside the Axios function. Here is a snippet of my component setup:

<template>
  <v-app>
    <AppBar />
    <router-view/>
    <Loader v-if="isLoading"></Loader>
  </v-app>
</template>

<script>
import AppBar from '../components/AppBar';
import Loader from '../components/Loader';
import axios from 'axios';

export default {
  name: "App",
  components: {
    AppBar,
    Loader
  },
  data() {
    return {
      isLoading: false
    }
  },
  created() {
    axios.interceptors.request.use(function (config) {

      this.isLoading = true;

        return config;
      }, function (error) {
        this.isLoading = false;
        return Promise.reject(error);
      });

    axios.interceptors.response.use(function (response) {
        this.isLoading = false;

        return response;
      }, function (error) {
        return Promise.reject(error);
      });
  }
};
</script>

Answer №1

Your current closures are referencing their own this context, which is not the intended context. To access the this context of the surrounding scope (in this case, your component state), consider replacing them with arrow functions like so:

axios.interceptors.request.use((config) => {
    this.isLoading = true;
    return config;
}, (error) => {
    this.isLoading = false;
    return Promise.reject(error);
});

Answer №2

The term this always points to the current scope. However, when utilized inside a function from the axios object, it loses its connection to your component. To resolve this issue, you can simply store that reference in a new variable.


created() {
  var vm = this;
  axios.interceptors.request.use(function (config) {

    vm.isLoading = true;

    return config;
  }, function (error) {
    vm.isLoading = false;
    return Promise.reject(error);
  });

  axios.interceptors.response.use(function (response) {
    vm.isLoading = false;

    return response;
  }, function (error) {
    return Promise.reject(error);
  });
}

Since this behaves differently in arrow functions compared to regular functions, I recommend checking out When should I use Arrow functions in ECMAScript 6? for further clarification.

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

Leveraging the power of AngularJS to run JavaScript functions saved as strings

Is it possible to dynamically inject JavaScript code that is stored in a string into AngularJS controllers? var dynamicJS = "function DoSomething(value){var x = 1+1 return 2;}" I need to inject the above function dynamically into my AngularJS controller ...

Refresh the page and witness the magical transformation as the div's background-image stylish

After browsing the internet, I came across a JavaScript script that claims to change the background-image of a div every time the page refreshes. Surprisingly, it's not functioning as expected. If anyone can provide assistance, I would greatly appreci ...

Ways to transmit the appropriate model

Using AJAX, I am sending a model to the server via a POST request. I have defined a model and a controller method for processing it. public class TestDto: BaseDto { [Required] public ProductGalleryDto GalleryProduct { get; set; } public int ...

Display a jQuery alert when an AJAX post request exceeds its timeout limit

I have been working on creating a feature to notify users when their $.post() request times out. To achieve this, I have implemented the following code snippet: //when ajax request start show overlay $(document).ajaxStart(function(){ ...

The system considers the resource as a script, yet it was transmitted with the MIME type of text

I am encountering an issue when trying to integrate AngularJS/JavaScript into my HTML document. Each time I try to load my index.html file, the following error message appears: Resource interpreted as Script but transferred with MIME type text/html: "http ...

Creating a collaborative storage space within a MERN project folder

Currently, I am developing an application using the MERN stack. The structure of my project repository includes both backend and frontend components: my-project/ ├── backend/ │ │ │ . │ . │ └── package.json ├── fronten ...

Trigger an Angular2 component function from an HTML element by simply clicking a button

I'm just starting out with TypeScript and Angular2 and encountering an issue when trying to call a component function by clicking on an HTML button. When I use the **onclick="locateHotelOnMap()"** attribute on the HTML button element, I receive this ...

Exploring the process of defining and authenticating an array of objects utilizing cuid as the key and ensuring the object contains designated properties

I have a customized data set that requires validation: { "name": "Some unique name", "blocks": [ {"cj5458hyl0001zss42td3waww": { "quantity": 9, "rate": 356.77, ...

transferring data from ejs template

In my app.js file, I have an array that stores files. To display these files on a website, I use a for-loop in ejs: <% for(let i = 0;i<posts.length; i++){ %> <li class="listtitle"> <%= posts[i].title %> </li> ...

AngularJS POST request encounters failure: Preflight response contains improperly formatted HTTP status code 404

I have encountered a persistent issue with microframeworks while attempting to perform a simple POST request. Despite trying multiple frameworks, none of them seem to handle the POST request properly: Here is an example using AngularJS on the client side: ...

Tips for optimizing ajax performance and creating a speedy ajax-loaded reply text field, similar to the one on Orkut

Greetings, I am currently working on a website where I would like to implement a reply user feature. How can I create an ajax loaded reply text field that behaves like a popup? Right now, the existing text field takes quite a long time to load when clicki ...

Sending a page identifier through a menu

Being new to vue/nuxt, I encountered an issue when setting up the frontend for a headless CMS. I have defined two routes as follows: Pages -StandardPage ->_standardPage.vue -InfoPage ->_InfoPage.vue Both my _standardPage.vue and _infoPage.v ...

Opting for Mysql over MongoDB as the provider in Next.js with Next-auth

Exploring the Next.js framework for the first time, I've dived into using Next-auth to handle sign-up/login functionality based on the provided documentation. My experience so far has been smooth, especially with the MongoDB provider as recommended i ...

Choose a date range from the date picker

I am currently attempting to combine two dates using a rangepicker. Below is the command used to select the date: Cypress.Commands.add('setDatePickerDate', (selector, date) => { const monthsShort = [ 'janv.', 'févr.& ...

Enhance an item by introducing additional properties derived from its current key-value pairs

I have a task of converting the following object: myObj = { "pageName": "home", "dataExtract": "data1|data2=value2|data3=value3|data4=value4a,value4b,value4c"} Into this format: myObjMod = { 'pageName': 'home', 'dataExtract&apos ...

effective ways to extract objects from nested structures using a specific identifier

In this sample data, I am looking to filter an object based on its ID key let myData = { "nodeInfo": { "9": { "1": { "ID": "14835" ...

I'm getting a "module not found" error - what's the solution?

const { getIo } = require('services/socketio'); const restful = require('utils/restful'); const publicApiService = require('services/publicApi'); const accessTokenMiddleware = require('middleware/accessToken'); const ...

Dynamic selection in Ajax using dependent selects

I have a functional first select box that displays two fields and another select box related to the user's choice. The second select box also populates with additional choices, requiring the user to make another selection. However, when it comes to ...

leveraging UI-Router for navigating based on app state and data

Is there a way to dynamically adjust Angular's ui-routing based on certain data conditions? For instance, let's say we need to create a subscription process where the user is informed of whether their subscription was successful or not. As the f ...

Steps for displaying a division on clicking a hyperlink

I am currently working on my main menu layout in HTML, and here is the code snippet: <div id="main-container"> <div id="main-wrapper"> <div id="logo"> <h1 id="title">port ...