Home > Back-end >  Mitt event bus, not working inside axios interceptor but works fine in my vue components
Mitt event bus, not working inside axios interceptor but works fine in my vue components

Time:06-20

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;

CodePudding user response:

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
                     
  • Related