Enhancing asynchronous loading with Axios interceptors

When utilizing vue.js along with the axios library to make requests to my API, I aim to configure it globally and display a loading message when the request takes too long.

I discovered that by using axios interceptors, I can set up axios configuration on a global scale.

axios.interceptors.request.use((config) => {
    // Perform actions before sending the request
    return config;
  }, (error) => {
    // Handle request errors
    return Promise.reject(error);
  });

// Add a response interceptor
axios.interceptors.response.use((response) => {
    // Handle response data
    return response;
  }, (error) => {
    // Handle response errors
    return Promise.reject(error);
  });

To display notifications, I rely on f3oall/awesome-notifications plugin (specifically the version for vue.js). Here's an attempt to incorporate it:

axios.interceptors.request.use((config) => {
    this.$awn.info("Attempting to send request");
    return config;
}, (error) => axios_error(error));

axios.interceptors.response.use((response) => {
    this.$awn.success("Success!");
    return response.data;
}, (error) => axios_error(error));

function axios_error(error) {
    //this.$awn.alert("Request error"); // This line throws an error - Uncaught (in promise) TypeError: Cannot read property '$awn' of undefined

    return Promise.reject(error);
}

However, I encounter some issues:

Firstly, I prefer not to use the success method to display success messages. Instead, I want to utilize the asyncBlock() method which displays a loader and blocks the screen until the promise is fulfilled, then triggers a callback or shows a new toast.

asyncBlock(promise, onResolve, onReject, html)

How can I implement this within the interceptors.request and interceptors.response functions?

Secondly, In the axios_error() function, I cannot access this. Thus,

this.$awn.alert("Request error");
does not work. Is there a way to resolve this issue?


All I want is to globally configure the following behavior: if a request exceeds 500ms in duration, display asyncBlock dots (a full-window loading message). If an error occurs during the request, show an error message - this.$awn.alert("Request error"). If no errors arise, do not display any messages.

Is there a way to achieve this? Are there any alternative approaches?

Answer №1

To begin with. One way to take advantage of the config object is by utilizing it in both request and response interceptors:

axios.interceptors.request.use((config) => {
    // Create a promise to use in asyncBlock
    config.loadingScreenPromise = new Promise((resolve, reject) => {
        config.resolveLoadingScreenPromise = resolve;
        config.rejectLoadingScreenPromise = reject;
    });
    this.$awn.asyncBlock(config.loadingScreenPromise, //... other params)

    return config;
}, (error) => axios_error(error));

axios.interceptors.response.use((response) => {
    // Fulfill loading screen promise
    response.config.resolveLoadingScreenPromise()

    return response.data;
}, (error) => {
    // Decline loading screen promise
    error.config.rejectLoadingScreenPromise(error)
    axios_error(error)
});

Second step. You can either directly invoke this.$awn.alert() from the error interceptor lambda function(to access Vue component's this) or pass this.$awn explicitly to axios_error function.

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

What might be causing the issue with my ajax request to the PHP file within the data parameter?

Although I am successfully getting my php value into a JavaScript variable, it seems like my script.js file is unable to find it. For the sake of brevity, some files have been omitted in this question. The main issue is that the script.js file retrieves th ...

How can I retrieve elements i from each array in HandlebarsJS and then access element j, and so on?

Given a JSON like this: { "network": [ { "name": [ "John", "Jill", "June" ] }, { "town": [ "London", "Paris", "Tokyo" ] }, { "age" : [ "35", "24", "14" ] } ] } Unfortunately, my data is in this format and I have to work w ...

Issue with function execution within useEffect() not being triggered

I am facing an issue where two functions in my component are not being called every time it renders, despite my efforts. Placing these functions in the dependency array causes an infinite loop. Can anyone identify why they are not executing? function Por ...

Modifying the color of an individual object in THREE.js: Step-by-step guide

I am currently working on editing a program that uses Three.js and Tween.js. Despite my efforts to find a solution both here and online, I have not been successful. The program involves creating multiple objects (cones) using THREE.Mesh, with a script that ...

The routes in Laravel and Vue.js seem to exist, but the DELETE and PUT methods return a 404 not found error

For some reason, I am encountering a "404 not found" error when attempting to perform PUT or DELETE requests, even though the route exists and everything was previously functioning correctly... My project is built on Laravel and Vue.js. All GET requests ...

Adding individual buttons at the bottom of each data row using Jquery: A step-by-step guide

Currently, I am receiving data from a backend using an AJAX GET method and displaying it in a list in HTML. However, I am facing some issues with including buttons within the list and making them functional by utilizing delegate and other methods. I would ...

Identifying the length of a division element following its addition

I'm facing difficulties in detecting the length and index of the dynamically appended div. I have researched extensively and found a solution involving MutationObservers, but I am unsure if it is necessary for this particular issue. Let's focus ...

Utilizing Jquery Validation to Remove a Class Upon Form Validation Success

In my current registration process, I have a multipart form where each subsequent form is displayed when the next button is pressed without fading effects. Initially, the button appears faded. Here's a simplified version of how I handle the first form ...

How to toggle the visibility of an element in an array using AngularJS and JavaScript

Is there a way to show additional information when an item in ng-repeat is clicked, and then hide this extra info when the mouse leaves that same item? One issue I am facing with the code snippet below is that when a user clicks on a different item, it al ...

Retrieve the image information from a specified element in the Document Object Model

Is it possible to extract the image data of a DOM element using standard JavaScript or browser extensions? I'm considering scenarios where: Creating an offscreen DOM element Populating it with dynamically styled CSS content Retrieving its image dat ...

Create a variable to store the sum value when iterating through a range using jQuery's

Currently, I am in the process of developing a specialized calculator that requires me to calculate the sum of variables within my jQuery.each loop for a specific range from 0 to 4 (equivalent to 5 years). While I have come across several informative reso ...

Revisiting Dynamic URL Parameters with React Router and Express

After setting up my React router to navigate '/Article/1/' via a link, everything seems to be working fine. However, I encountered an issue when refreshing the browser as it no longer detects my Article component. MainApp.js import React from & ...

How do I repeatedly invoke a function in JQuery that accepts two different arguments each time?

I have a collection of folders, each containing various images. The number of pictures in each folder ranges from 8 to 200. Folders are numbered from 1 to 20 and the images within them are also labeled numerically. My goal is to aggregate all these images ...

Methods for eliminating curly braces from HTTP response in JavaScript before displaying them on a webpage

When utilizing JavaScript to display an HTTP response on the page, it currently shows the message with curly braces like this: {"Result":"SUCCESS"} Is there a way to render the response message on the page without including the curly braces? This is the ...

Javascript cards arranged in descending order

I'm in the process of developing a sorting feature that arranges cards in the DOM from Z to A with the click of a button. Although I've successfully implemented the logic for sorting the array, I'm facing difficulties in rendering it. Withi ...

Implementing Security Measures for ExpressJS Static File Server

Recently, I set up an authentication system following a tutorial on express.js and passport.js. In the past, my express server setup used modRewrite as shown below: var express = require('express'); var modRewrite = require('connect-mod ...

Javascript - Button animation malfunctioning after first click

One issue I'm facing is with an animation that is triggered using the onmousedown event. Another function is supposed to stop the animation when onmouseup is detected. The problem arises after the first time it works correctly. Subsequent attempts to ...

Ways to insert additional panels prior to and after a selected panel

A button is provided in the report designer detail band that, when clicked, should add new panels immediately before and after the detail panel. $parentpanel = $this.parents(".designer-panel:first"); This code snippet is used to locate the parent panel u ...

Unable to retrieve the value from the selected radio button

Below is the provided HTML: <form> <div class="form-group"> <div class="checkbox-detailed male_input"> <input type="radio" name="gender" id="male" value="male"> <label for="male"> ...

Dynamic Element with Mousewheel Event

Simply put, I am attempting to attach a 'mousewheel' event to a div that contains a scrollbar. My code functions properly when used outside of the plugin I developed, but as soon as I convert it into a plugin, it stops working. I tested changing ...