Making a Request on Behalf of a Component in Vue.js Using Interceptors

Within my Vue application, I've implemented a response interceptor:

axios.interceptors.response.use(function (config) {
        return config;
    }, error => {
        if (error.response.status !== 401) {
            return new Promise((resolve, reject) => {
                reject(error);
            });
        }

        if (error.response.status === 401 && error.response.data.message === 'Token Expired') {
            this.store.dispatch('auth/refreshToken').then(aToken => {
              var config = error.config;
              axios.defaults.headers.common['Authorization'] = 'Bearer ' + aToken;

              return new Promise((resolve, reject) => {
                axios.request(config).then(response => {
                  console.log(response);
                  resolve(response);
                }).catch((error) => {
                  reject(error);
                });
              });
            });
          }
    });

The focus here is on refreshing the token and reattempting the last request with the updated token.

An issue arises when considering a specific component, Product.vue. For example, a request is made to the /products endpoint upon mounting this component. The retrieved products are stored in a data variable called products. If a user is currently on the /dashboard route and their session expires while they're away, a subsequent visit to the /products route triggers a 401 response interception event. The interceptor will update the token and retry the failed request with the new token.

The challenge lies in the fact that the new API call triggered by the interceptor doesn't originate from the original Product component. As a result, any retrieved data is lost, leading to an empty view for the end-user.

Is there a method to identify the component responsible for the initial request within the interceptor and trigger a remount? Attempts such as using $router.push('/products') lead to navigation restrictions due to being already on the target route.

Alternatively, is it possible to manage the promise returned by the interceptor within the Product component?

Answer №1

To keep the promise chain running smoothly, make sure to return the dispatch promise in order to avoid any disruptions.

axios.interceptors.response.use(success => success, error => {
  if (error.response.status === 401 && error.response.data.message === 'Token Expired') {
    // Include a new promise
    // The specifics of "this" and "store" may be uncertain, but it's your code after all
    return this.store.dispatch('auth/refreshToken').then(token => {
      axios.defaults.headers.common.Authorization = `Bearer ${token}`
      return axios.request(error.config)            
    })
  }
  return Promise.reject(error)
})

In simpler terms, Axios' response interceptors are like additional steps in the promise chain that occurs before your code receives the data...

return axios.request({ ... })
  .then(successInterceptor)
  .catch(errorInterceptor)

Your focus is only on handling successful responses by directly returning the original result:

success => success

On the other hand, the error interceptor will address expired token issues by initiating a new promise, starting with token renewal followed by repeating the initial request (Promise chaining).

If the error is not related to an expired token, maintaining the rejected promise ensures consistency. Failing to do so can lead to misleading outcomes for your calling code 🙂.

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

Can JavaScript be used to dynamically assign events to elements on a webpage?

I am currently using the following code: if ( $.support.touch == true ) { $(window).on('orientationchange', function(event){ if ( full == false ) { self.hideAllPanels("7"); } }); } else { $(window).on(&apo ...

The pdfkit library seems to have an issue where it is failing to properly embed images within the

Currently, I am working on using PDFkit along with node.js for converting an HTML webpage into a PDF format. The HTML page contains multiple image tags within the body tag. Unfortunately, when I convert the HTML to PDF, the resulting page appears complete ...

Tips for sending a parameter within a JavaScript confirm method?

I currently have the following code snippet in my file: <?php foreach($clients as $client): ?> <tr class="tableContent"> <td onclick="location.href='<?php echo site_url('clients/edit/'.$client->id ) ?>&ap ...

What are the steps to utilize the feature of "nprogress"?

After successfully installing npm install nprogress in my project, I encountered an issue when trying to refresh the page - the console displayed the following message: hot-dev-client.js:182 [Fast Refresh] done hot-dev-client.js:196 [Fast Refresh] rebuildi ...

Utilizing negative values in lineTo, strokeRect, and fillRect functions

Is it possible to input negative numbers into the drawing primitives of HTML5 canvas? For instance, if I apply a translation of (100,100), would I be able to draw a rectangle or line with coordinates (-25,-25)? Initial testing using lineTo seems inconclus ...

Tips for using the Enter key to shift focus to the next input field

I am trying to move to the next input field when I hit the enter key. I found a solution in another question here, but the code provided doesn't work for me because my input fields are inside a table. Here is my HTML code: <form action="#"> < ...

I am encountering difficulties with importing Node modules into my Vue.js project

Having some trouble importing a node module via NPM in a Vue.js single file component. No matter which module I try to install, it always throws an error saying These dependencies were not found. I'm following the installation instructions correctly ( ...

What could be the reason for the Azure server sending a Bad Request response?

My NodeJS application is currently hosted on Azure server and all APIs are functioning correctly, providing the expected responses. The issue arises when trying to run a GET API like the following: https://demoapp.azurewebsites.net/mymenu?userId=piyush.d ...

Executing a JavaScript function within a React web application

Having trouble calling JS functions from ReactJS? I recently encountered an issue when trying to import and call a JS function in a button onClick event in my React project. Specifically, when trying to use this.abtest.events.on in the handleButtonColor fu ...

Ways to avoid data looping in jQuery Ajax requests

This is in relation to the assignment of multiple users using the Select2 plugin, Ajax, and API. The situation involves a function that contains 2 Ajax calls with different URLs. Currently, there are pre-selected users stored in the database. The selection ...

Utilizing React-map-gl in combination with either useContext or useState to update the viewport from a separate component

Lately, I've been struggling to understand how to use useContext and/or useState with React/Nextjs along with react-map-gl. In my project, I have a searchbox component that uses Formik and a map component from react-map-gl. What I'm trying to ach ...

Can you guide me on how to establish a cookie within a selenium webdriver javascript script?

I am trying to figure out how to set a cookie using a basic webdriver script: WDS.sampleResult.sampleStart(); //WDS.driver.manage().addCookie(new Cookie("connect.sid", "s%3AeexeZcd_-S23Uh30e3Dmd4X9PskWF08s6m5hDurDa5Jj66SupmmiqvKEjAg6HGigl0o0V%2B9R7m4", ...

JavaScript error: You are trying to use Array.find() in Redux, but it

I am currently developing a react native application and I am using basic redux for managing the state, although I am a complete beginner to this. In a specific issue, I am facing an issue while fetching data from my redux store in the edit screen where th ...

Issue TS1259: The module "".../node_modules/@types/bn.js/index"" can only be imported as the default using the 'esModuleInterop' flag

Currently, I am utilizing Hiro Stack.js which I obtained from the following link: https://github.com/hirosystems/stacks.js/tree/master/packages/transaction. For additional information, please refer to . Even when attempting to compile a fully commented out ...

Delete the item along with its associated data from the local storage upon clicking on an icon

I'm currently working on a To-Do List and facing an issue while trying to delete an item upon clicking a trash bin icon. image The problem I'm encountering is that only one data point is removed from local storage when the icon is clicked. If I ...

Error alert: Index not defined!

I have a dropdown select that needs to be populated with values from a database. I then need to validate the selected value using a JavaScript function, which is already implemented. The dropdown list has two columns: one for ID identifiers and another fo ...

Best approaches for communicating form-data between parent and child components in VueJS

I am currently working on a VueJS project that involves parent and child components structured like this. Parent.vue <template> <ChildA v-bind="this.postData.someDataA" /> ... <ChildZ v-bind="this.postData.someDataZ"/> & ...

What's a way to pass a PHP variable directly to Javascript without using AJAX?

In my setup, I've implemented a JavaScript code that validates and sends the 'artwork' file to a PHP script on my server. This PHP script also performs its own checks for redundancy before writing the file to /uploads directory. The challen ...

Rendering Next.js app within HTML markup provided as a string

I am facing a challenge with integrating my Next.js app into an external HTML markup. The provided markup structure consists of the following files: header.txt <html> <head> <title>Some title</title> </head> < ...

Building a dynamic webpage using AJAX, MVC, and web APIs to generate a div element filled

I'm currently working with a restful API, MVC, and ajax. My goal is to retrieve data from the backend and then display images within certain div elements. The expected outcome should resemble this example: https://i.stack.imgur.com/BFqWL.png This sni ...