Home > Blockchain >  Why axios.interceptors call many times? React Native
Why axios.interceptors call many times? React Native

Time:12-04

This is what i came up with , but everytime i try to move around my screens in my app and do api calls its sends 3 console logs with the interceptors calls.

  1. The 1st Api call only sends 1 request but after it sends 3/4 calls of interceptors
  2. Im using Expo with react Native
let axiosInterceptor = null;
    
    axiosInterceptor = axios.interceptors.request.use(function (config) {

        if (!!axiosInterceptor || axiosInterceptor === 0 || axiosInterceptor >= 1) {
            axios.interceptors.request.eject(axiosInterceptor);
            
        }

        if (config.url == "login/login") { //quando faz login não necessita dos headrs de autorização (Bearer Token)
            return config;
        }
        setIsLoading(true);
        //global.isWaitingRequestAnswers = true;
        //console.log("request isWaitingRequestAnswers", global.isWaitingRequestAnswers);
        const configToken = SecureStore.getItemAsync('token').then(token => {
            console.log("Axios Call: "   config.url)
            // console.log("Axios Call Token: " token)
            // console.log(token)
            config.headers.Authorization = 'Bearer '   token;
            return config;
        });
        return configToken;

    }
        , function (error) {
            console.log('Error => axios.interceptors.request');
            console.log(error);
        });

**Updated **

Axios Call

**Updated 1 **

 async function getInventario () {

var dados = null;
await axios.get('inventario/index')
.then((response) => {
    dados = response.data;
})
.catch((error) => {
    console.log(error)
});
return dados;

}

Network Reponse

axios.interceptors.response.use(response => {
    setIsLoading(false);
    //global.isWaitingRequestAnswers = false;
    //console.log("response isWaitingRequestAnswers", global.isWaitingRequestAnswers);
    return response;
}, error => {
    if (error.response.status === 401) {
        authContext.signOut(); //logout -> go to Login Page
    }
    console.log('Error => axios.interceptors.request');
    console.log(error);
});

i have this code in the end it could help!

CodePudding user response:

Looks like you're using this code in a React component preferably you have to place this code outside any React lifecycle.

CodePudding user response:

SecureStore.getItemAsync('token') is asyncronous, you must wait response, change headers and then return config but your code do it syncronous. As a result headers is not updated yet but you returned config already. Example with async/await:

const CancelToken = axios.CancelToken;
let axiosInterceptor = false;
let requests = [];

const instance = axios.create();   
instance.interceptors.request.use(async (config) => {

if (config.url === "login/login") {
    return config;
}

requests.push(config);

if(!axiosInterceptor) {
  axiosInterceptor = !axiosInterceptor;
  setIsLoading(true);

  const token = await SecureStore.getItemAsync('token');
  axiosInterceptor = !axiosInterceptor;
  requests.map(req => {
    req.headers.Authorization = 'Bearer '   token;
    return instance(req)
  });
 }
 requests = [];
 return {
    ...config,
    cancelToken: new CancelToken((cancel) => cancel('Cancel repeated 
    request'))
 };
}, function (error) {
    console.log('Error => axios.interceptors.request');
    console.log(error);
});
  • Related