Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Axios interceptors - Not using instance until AsyncStorage resolved?

I've an Axios Interceptor setup to manage responses and cut down on re-writing code everywhere. Currently, I need to add the Authorization header using the { config } object in each call like below.

apiCall = () => {
    const token = await AsyncStorage.getItem('JWT_BEARER_TOKEN');
    const config = {
      headers: {
        'Authorization': 'Bearer ' + token,
      }
    }
    const attendance = await axiosInstance.post('/team/matchday', data, config);
    // ... do something with attendance
}

I'd like to do it in the axiosInstance I've create as below, but I'm getting a promise rejected error. I presume this is because token is still an incomplete promise when it is returned.

Any ideas how to handle this config correctly?

import { AsyncStorage, Alert } from 'react-native';
import axios from 'axios';


const ReturnAxiosInstance = async (token) => {
  const AxiosInstance = axios.create({
    baseURL: 'http://localhost:4000',
    timeout: 3000,
    headers: {
      'Content-Type': 'application/json',
      'Authorization': 'Bearer ' + await AsyncStorage.getItem('JWT_BEARER_TOKEN'),
    },
  });

  AxiosInstance.interceptors.response.use(
    response => response,
    (error) => {
      if (!error.response) {
        Alert.alert('Network Error!');
        return console.log(error);
        // return dispatch({ type: 'NETWORK_FAILURE' });
      } else if (error.response.status === 500) {
        Alert.alert('Server Error!');
      } else if (error.response.status === 404) {
        Alert.alert('Endpoint doesn\'t exist!');
      }
      // handle the errors due to the status code here
      return error.response;
    },
  );
  return AxiosInstance;
};
export default ReturnAxiosInstance();
like image 775
denden Avatar asked Apr 17 '18 13:04

denden


1 Answers

You need to add in the request interceptor for your Axios instance.

 // ...
 axiosInstance.interceptors.request.use(
    async (config) => {
      config.headers.authorization = await AsyncStorage.getItem('JWT_BEARER_TOKEN');
      return config;
    },
    error => Promise.reject(error)
  );
  // ...
like image 127
denden Avatar answered Jan 04 '23 16:01

denden