Twice as Many Alert() Pop-Ups in Axios Interceptor (Vue.js)

In my Vue application, I have set up a single axios instance to handle all HTTP requests across the app. There is a response interceptor in place that checks for any 401 unauthorized responses from the back end and displays an alert message accordingly. However, I am facing an issue where I have to click "OK" on the alert message twice for it to disappear, and I'm unsure of the cause.

Here is the Axios instance code:

import axios, { AxiosError, AxiosInstance, AxiosResponse } from 'axios';

const axiosInstance: AxiosInstance = axios.create();

axiosInstance.interceptors.response.use(
  (response: AxiosResponse) => response,
  (error: AxiosError) => {
    if(error.response && error.response.status === 401) {
      alert('There has been an issue. Please log out and then log in again.');
      return Promise.reject(error);
    }
  }
);

export default axiosInstance;

The request being intercepted:

import axiosInstance from 'axios-instance';

public async getloggedInUserId() {
  await axiosInstance.get('/sessions.json')
    .then((response) => {
      if(response.data.user_id) {
        this.SET_USER_ID(response.data.user_id);
      }
    });
}

I have looked into similar threads such as Javascript alert shows up twice, but my situation appears to be different. I attempted changing the return statement from return Promise.reject(error); to return false; without success.

Answer №1

After taking Phil's advice from the previous comment, I found that checking the Network tab in the browser console was the key to resolving the issue at hand. By analyzing this section, I could see how each component on the page was loading and the corresponding response codes it generated. As it turns out, two processes were returning a 401, leading to the alert being triggered twice.

To address this problem, I made the decision to relocate the part of the code responsible for invoking the alert from a global axios interceptor (which was activated whenever any process returned a 401) to a .catch block within a specific axios process. This adjustment ensures that the alert is only triggered once.

Answer №2

An error is triggered by your commitment within the axios error interceptor, resulting in a second instance of the error being called.

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

Switch from using color-adjust to print-color-adjust. The color-adjust shorthand is now obsolete

Can anyone help me troubleshoot this warning that appears when I'm creating a new Laravel project? To replicate the issue, follow these steps: Run `composer create-project --prefer-dist laravel/laravel example` Navigate to the `example` directory Ru ...

Exploring Vue Component Features through Conditional Display

I am working with a vue component called <PlanView/>. In my code, I am rendering this component conditionally: <div v-if="show_plan" id="mainplan"> <PlanView/> </div> <div class="icon" v-else> ...

Restricting Entry to a NodeJS Express Route

Currently, I am in the process of developing an express project where I have set up routes to supply data to frontend controllers via ajax calls, specifically those that start with /get_data. One issue I am facing is how to secure these routes from unauth ...

Is there a way to dynamically insert the user's id into the URL section of an AJAX request?

Seeking to make the '2' in the url field of the getEvents function dynamic by replacing it with the current user's id. I was thinking of using ${current_user.id}. Can someone guide me on how to achieve this? Ideally, I'm aiming for som ...

How to identify and handle the invalid control within an Angular(v2 onwards) reactive form Form Array

When this.from.valid returns false, I utilize the following approach to identify the first invalid control and handle the error in my component. While this method works well for form groups without any form array, is there a way to identify the first inval ...

Steps for creating a TypeScript class that can implement an interface

As a beginner in TypeScript, I am looking for help with the following code snippet: async function sleep(ms: number) { return new Promise((resolve, reject) => { setTimeout(() => resolve(), ms) }) } async function randomDelay() { ...

When an array is passed into a Vuex action function, it transforms into something other than just

EDIT: Added extra code in the filterEvents snippet for more context. I'm struggling to understand the behavior of my code. My goal is to pass an array into an action function within my Vuex store. However, when I return a Promise inside that action f ...

Substitute a variable within a script with another variable located on the same page (JS/PHP)

I am trying to modify a script that was generated by a Wordpress plugin: <script type='text/javascript'> if (typeof(jQuery)=="function") { (function($) { $.fn.fitVids=function(){}})(jQuery) }; jwplayer('jwplayer-0').s ...

`Weaving mesh into place with three.js`

I'm struggling to grasp how to position my cubes on the canvas. I can't quite figure out how positioning actually works. I'm trying to find a way to determine if my mesh reaches the limits of the canvas. But what exactly is the unit of posit ...

Is it possible for @load to trigger once the component has been dismounted?

Hey there, I'm currently working on a Vue 3 app and I've come across some unusual behavior that's leaving me puzzled. I have a question in mind: Can the @load event trigger after the component has been unmounted? If so, what steps can be ...

Encountering ArrayExpression problem during migration from version 1.5.2.2 to 1.6

I recently updated my Meteor version from 1.5.2.2 to 1.6 and encountered the following error message: /home/mai/.meteor/packages/ecmascript/.0.9.0.l8rb8s.l2n4++os+web.browser+web.cordova/plugin.compile-ecmascript.os/npm/node_modules/meteor/babel-compiler/ ...

Changing the Div heights in Material UI with grid layout customization

I have a project that requires me to implement material-ui. Is there a way I can adjust the width and height of the div containing the "Sign In With" text (as shown in the first image) to bring the buttons closer to the text? Transformation from this: ht ...

In the MEAN.io framework, what is the relationship between public controllers and server controllers?

Just getting started with MEAN.io and they include a sample "articles" model that resembles a typical blog post with a title and body. Included in the example is an index.html file that showcases a list of articles upon navigation. Within this file, there ...

The phrase 'tsc' is not identified as a valid cmdlet, function, script file, or executable program

Recently, I attempted to compile a TypeScript file into a JavaScript file by installing Node.js and Typescript using the command "npm install -g typescript". However, when I tried to compile the file using the command tsc app.ts, an error occurred: tsc : T ...

What is the best way to instantiate a service (injectable) with Angular within a class?

import { Store } from '@ngxs/store'; export class Service { constructor(private _store: Store) {} } export abstract class A { constructor( private _service: Service ) { } } export class B extends A { constructor( private _service: ...

ThymeLeaf fails to display the elements of a List

I am struggling with a complex HTML structure in my project. The HTML code includes a mix of Bootstrap classes and Thymeleaf attributes. Additionally, there is a JavaScript function that interacts with radio buttons to show or hide elements based on user i ...

When importing OrbitControls in main.js, THREE.js does not include the EventDispatcher export

Description I've been working on integrating the OrbitControls from THREE.js into my project. However, I encountered an error message in the Google Chrome DevTools console when trying to import the OrbitControls object. The requested module '. ...

Guide on automatically closing child menu items in a sidebar using Vue.js

One issue I am facing is with my sidebar that contains children elements. The problem occurs when I click on a menu and then have to click on it again to close it. Is there a way to make it so that when I click on another menu, all of the children sidebar ...

Extremely sluggish change identification in combination Angular application

We are encountering consistent issues with slow change detection in our hybrid AngularJS / Angular 8 app, especially when dealing with components from different versions of the framework. The problem seems to arise when using older AngularJS components wit ...

Select component experiencing issue with Material Ui label breaking

I've been working on implementing a select component, which is new to me. However, I'm encountering an issue with my MUI-select component. The label of the select element is no longer syncing properly with the select component itself as shown in ...