I am trying to implement a interceptor with axios so everytime I receive a response from a request, it checks if it has the field "msg" and if it has, it should show the message to the user.
To do this, I implemented a interceptor in axios, this interceptor should fire an event everytime it receives a response, then the App.js
would be listening to this events to show the appropriate message.
My problem is that it seems the event is being fired twice, at first I though it was a problem with PubSub, which is the library that I was using, so I decided to try another framework (eventemitter3) and the exact same thing happened, so I'm totally lost, other people who had similar issues found out that their requests werte actually being fired twice by different components, I'm almost sure that this isn't the problem here, look at the logs when I make a request:
interceptor > Object { data: {…}, status: 200, statusText: "OK", headers: {…}, config: {…}, request: XMLHttpRequest }
intercepted by eventemitter3 > Object { data: null, msg: "Usuário não encontrado", success: true }
intercepted by eventemitter3 > Object { data: null, msg: "Usuário não encontrado", success: true }
intercepted by pubsub > Object { data: null, msg: "Usuário não encontrado", success: true }
intercepted by pubsub > Object { data: null, msg: "Usuário não encontrado", success: true }
notice that there is one "interceptor" log, which means only one request was intercepted, then one event is fired for eventemitter3 and one event is fired for pubsub. The networks tab of the browser only shows one POST and one OPTIONS request. Here is my axiosInstance:
import Axios from 'axios';
import PubSub from 'pubsub-js'
import Emitter from './EventHandler';
export const axios = Axios.create({
baseURL: "http://localhost/api"
})
axios.defaults.headers.common['Authorization'] = localStorage.getItem('jwt') || "";
axios.interceptors.response.use(function (response) {
console.log("interceptor",response)
Emitter.emit('RESPONSE_INTERCEPTED', response.data);
PubSub.publish('RESPONSE_INTERCEPTED', response.data);
return response;
}, function (error) {
return Promise.reject(error);
});
and here is App.js where I listen to the events:
export default function App() {
const alert = useAlert()
Emitter.on('RESPONSE_INTERCEPTED', (data) => {
console.log("intercepted by eventemitter3", data)
alert.show(data.msg)
});
var responseNotifier = function (msg, data) {
if(data.msg){
console.log("intercepted by pubsub", data)
}
};
var token = PubSub.subscribe('RESPONSE_INTERCEPTED', responseNotifier);
return (
<Router>
<div>
<Switch>
<Route path="/sobre"><Sobre /></Route>
<Route path="/memorias"><Memorias /></Route>
<Route path="/login"><Login /></Route>
</Switch>
</div>
</Router>
);
}
just in case it matters, here is the EventHandler
for eventemitter3:
import EventEmitter from 'eventemitter3';
const eventEmitter = new EventEmitter();
const Emitter = {
on: (event, fn) => eventEmitter.on(event, fn),
once: (event, fn) => eventEmitter.once(event, fn),
off: (event, fn) => eventEmitter.off(event, fn),
emit: (event, payload) => eventEmitter.emit(event, payload)
}
Object.freeze(Emitter);
export default Emitter;
and the piece of code that makes the request:
login(){
axios.post('/login', {
"username": this.state.username,
"password": this.state.password
}).then((resp)=>{
// console.log(resp)
})
}
I'm really clueless here, everything I found on SO/Google points to requests being fired twice, but the whole application is still in the begining, the code aboce is the only plaec where I fire a request, and the network tab confirms this, I'm fine using whatver event framework or even a completely different solution, I just need to show the message to the user, if someone can point me what I'm doing wrong here It would be of great help for me. Thank you all!