Search code examples
react-nativeaxiosasyncstorage

When create Axios instance, how to assign value from async storage in my case


In my react-native project, I use async-storage to store authorization token . I use Axios as HTTP client library, when I set up the header, I would like to use empty string as the value for header Authorization if there is no value stored in AsyncStorage. Otherwise use the value from the storage.

Below is the code I tried, but I get stuck on how to put the code for fetching the value from storage since it is an await call. I can't put it like it is now, compiler complains. But the export Axios is an object in the file. So, any suggestions?

import AsyncStorage from '@react-native-community/async-storage';
import {STORAGE_KEYS} from '../constants';

// I can't put this line here
const myToken = await AsyncStorage.getItem(STORAGE_KEYS.MyToken);

export default Axios.create({
  baseURL: 'http://192.168.10.207:3000',
  headers: {
    Authorization: myToken ? myToken : '',
  },
});

Solution

  • Axios Interceptors

    One solution would be to use Interceptors : https://github.com/axios/axios#interceptors

    import AsyncStorage from '@react-native-community/async-storage';
    import {STORAGE_KEYS} from '../constants';
    import axios from 'axios;
    
    const instance = return axios.create({ baseURL: 'http://192.168.10.207:3000' });
    
    instance.interceptors.request.use(async function (config) {
    
      const myToken = await AsyncStorage.getItem(STORAGE_KEYS.MyToken);
      config.headers['Authorization'] = myToken ? myToken : '';
      return config;
    
    });
    
    export default instance; 
    
    

    (not tested)