The event bus I'm using isn't functioning properly within the axios interceptor, yet it operates smoothly in all my Vue components

Currently, I am utilizing VueJs and mitt for the eventBus. The mitt is globally loaded and functioning correctly as shown below:

main.js

const emitter = mitt();

const app = createApp(App)
app.config.globalProperties.emitter = emitter

I am able to call the eventBus in all components successfully like this: this.emitter.emit('eventName', data)

However, I encountered an issue when trying to use it within an axios interceptor, resulting in an error (undefined).

My client.js (axios instance) is structured as follows:

const client = axios.create({
    // withCredentials: true,
    baseURL: ((authenticated.data.domain !== null) ? authenticated.data.domain : 'http://mydomain.test/api')
});

client.interceptors.response.use((response) => {
      // the problem occurs here 
     this.emitter.emit('alert', response.data);

    return response;
}, (error) => {
    return Promise.reject(error.message);
});

export default client;

Answer №1

app.config.globalProperties is utilized for creating global properties off of Vue component instances (rather than global properties off of window). Attempting to use the global event bus within your Axios instance is incorrect, as the this in the arrow function is undefined.

One potential solution is to separate out the event bus and import it where necessary:

// emitter.js
import mitt from 'mitt'
export default mitt()
// main.js
          👇
import emitter from './emitter.js'

const app = createApp(App)              👇
app.config.globalProperties.emitter = emitter
// client.js
         👇
import emitter from './emitter.js'
⋮
client.interceptors.response.use((response) => {
       👇
    emitter.emit('alert', response.data);

    return response;
}, (error) => {
    return Promise.reject(error.message);
});

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

Tips on how to automatically resize the browser window to a specific width and height once it has been minimized

If a JSP page is minimized onload, we need to find a way to restore it through a JavaScript call. Are there any other methods available for achieving this? The restoration should be to the height and width selected by the user. I have attempted the followi ...

The Node.js application successfully receives an emit event from the browser, however, the browser does not receive any emit

I'm having trouble understanding why the node.js server can connect and receive an emit() from the browser, but when I try to emit() back from node.js it doesn't reach the browser. Am I overlooking something here? The console log displays "Test ...

Having trouble deciding between JSON, XML, or using a database?

As I work on developing an app that involves sending an id and receiving a JSON node from PHP, I am considering the best approach for storing my data. Should I keep it as a static PHP array as shown in the code below, or should I save the data to an exte ...

When modifying the state of an array within a component, certain values may be overwritten and lost in the process

Currently, I'm faced with the challenge of ensuring that a component displays a loading screen until all images have completed loading. This is necessary because there are approximately 25 images that must finish loading before the page can be display ...

Tips for generating a numeric whole number input field with Vuetify

After researching the topic on Vuetify's specific number input component, I am attempting to create a numeric input field. The value for both input and output is currently unknown, meaning it could be either undefined or null in order to allow cleari ...

One way to organize data from my API is by sorting it based on two date conditions. If one of those conditions is missing, the data should be placed at the beginning of the list

I am facing a challenge with sorting the return from my API based on the StartDate. However, I need to implement a validation where if there is no FinalDate provided, the data should appear at the first index of the result. StartDate: "2004-06-04" ...

How can data on the server be fetched using an AJAX request in Express.JS and displayed on the client side?

I have been given the task of displaying this code on the client side. I've successfully loaded data/content on the page but it lacks a certain level of elegance. var express = require('express'); router = express.Router(), ...

Bootstrap-vue throws an error when Vue is not defined

Recently, I integrated bootstrap-vue into my Vue.js project by running the command yarn add bootstrap-vue bootstrap axios. Here is a snippet of my code: https://i.stack.imgur.com/oTBxn.png Another part of the code can be found here: https://i.stack.imgur ...

Adding items to an array within a jQuery each loop and performing a jQuery ajax request

I am trying to loop through an array, push the results into a JavaScript array, and then access the data outside of each loop and AJAX call. Can anyone explain how to do this? This is what I have attempted: var ides = ["2254365", "2255017", "2254288", ...

Ensuring the Accuracy of POST Parameters Using Express-Validator

I've been working on adding parameter validation to my Node/Express API by utilizing express-validator. However, I encountered a situation where even though I sent a POST request with a missing "name" field using the curl command curl -X POST -d "foo= ...

Error loading Azure Active Directory web form: Server returned a 401 status code for the requested resource

I recently made changes to my web site (incorporating a web form and entity framework) to use AAD connection, following the guidance in this insightful blog post. However, I am encountering an issue where scripts and css files are not loading properly. Th ...

How can I correctly connect a JavaScript library that has been installed via npm?

After using npm to install a JS library, such as: npm install chartjs The necessary JS file is typically located at ./node_modules/chartjs/chart.js. If you prefer the file to be in a different location, like ./public/js/chart.js, you could manually m ...

Axios: Exception handling does not involve entering the catch method

Implementing a function to adjust a contract name involves making an axios request to the backend API using a specific ID. Upon each execution, a sweetalert prompt is displayed. axios({ url: '/api/contract/' + id, method: 'put ...

When altering a single scope variable in AngularJS, the effect cascades to impact other scope variables as well

After uploading my code on fiddle, I noticed that changes made to the myAppObjects variable also affect another variable. Here is the link to the code: https://jsfiddle.net/owze1rcj/ Here is the HTML part of the code: <div ng-controller="MyCtrl"&g ...

Display the output of JSON.stringify in a neatly formatted table

After sending my table data to the database using ajax, I am now trying to retrieve it by clicking on the open button. $.ajax({ type: "POST", url: "http://localhost/./Service/GetPageInfo", dataType: "json", ...

"Utilize Ajax to dynamically generate options in a dropdown menu with multiple

I am having trouble populating my multiple dropdown list using AJAX. The dropdown list is dependent on another single selection dropdown list. Here is the HTML code: <div class="form-group"> <label for="InputGender">Select Course</ ...

Displaying currency format in an input field using AngularJS filter

I'm currently dealing with an input field that looks like this: <input type="text" class="form-control pull-right" ng-model="ceremony.CeremonyFee | number:2"> Although it is displaying correctly, I've noticed that it's disabled. The ...

Design a circular progress bar with a cut-off at the bottom

Does anyone have suggestions on how to create a circular progress bar with cropping at the bottom, similar to this example: PROGRESS BAR? I've been searching for a component like this but haven't had any luck. Any ideas, especially utilizing Mate ...

What could be causing the EBUSY: resource busy or locked, open errno: -4082 error to appear while trying to build storybook 7 in next.js 13?

While attempting to create a storybook, I encountered the following error in my project: [Error: EBUSY: resource busy or locked, open 'C:\Users\ali\Desktop\Works\Design Systems\projects\storybook-test2\node_modu ...

Executing functions with directive controllers

Is there a simple way to call a function on a directive controller by accessing the instance using its id from the parent controller? <my-directive id="id1" /> var dirController = getDirectiveByID("id1"); dirController.someFunc(); If you have any ...