Skip to content
Advertisement

Mitt event bus, not working inside axios interceptor but works fine in my vue components

I’m working with VueJs and mitt for the eventBus, the mitt is loaded globally as you can see and works fine :

main.js

const emitter = mitt();

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

I call the eventBus in all my component like that : it works fine this.emitter.emit(‘eventName’, data)

My problem is when I use that inside axios interceptor I get an error ( undefined )

my client.js ( axios instance )

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

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

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

export default client;

Advertisement

Answer

app.config.globalProperties is used to create globals off of Vue component instances (not globals off window). You’re incorrectly trying to use the global event bus in your Axios instance, as the this in that arrow function is undefined.

One solution is to factor out the event bus, and import it where needed:

// 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);
});
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement