Search code examples
reactjsreact-nativeaxiosinterceptorasyncstorage

Add Interceptors to instance of axios


I'm trying to update my app token on axios interceptors, using React Native. I have this code to connect to API back-end:

const requestHelper = axios.create({
  baseURL: "http://192.168.0.15:8000/api/",
  headers: {
    "Content-Type": "application/json",
    Authorization: "token 3260b30bdbc19a5c4deed87327536e443c751d27",
  },
});

const routes = {
  accounts: {
    getUser: () =>
      requestHelper({
        method: "get",
        url: "accounts/detail/",
      }),
.....

This is working but the token is hardcoded. I now need to update that token from AsyncStorage every time an API call is requested. I was trying to use Axios interceptors but is not working. These are my tests:

const requestHelper = axios.create({
  baseURL: "http://192.168.0.15:8000/api/",
  headers: {
    "Content-Type": "application/json",
  },
});

const createInterceptors = (instance) => {
  instance.interceptors.request.use(
    (config) => {
      config.headers = {
        Authorization: "token 3260b30bdbc19a5c4deed87327536e443c751d27",
      };
      return instance;
    },
    (error) => {
      return Promise.reject(error);
    }
  );
  return instance;
};

const routes = {
  accounts: {
    getUser: () =>
      createInterceptors(
        requestHelper({
          method: "get",
          url: "accounts/detail/",
        })
      ),
....

The token is hardcoded here too, but for testing purposes. This tests raise an error:

[Unhandled promise rejection: TypeError: undefined is not an object (evaluating 'instance.interceptors.request')]

Does anyone know how this could be implemented?


Solution

  • I solved it. I have to add the interceptor function like this:

    const requestHelper = axios.create({
      baseURL: "http://192.168.0.15:8000/api/",
      headers: {
        "Content-Type": "application/json",
      },
    });
    
    requestHelper.interceptors.request.use(async (config) => {
      const token = await AsyncStorage.getItem("token");
      config.headers = {
        Authorization: "token " + token,
      };
      return config;
    });