Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create Axios instance with taking token from AsyncStorage

In my React Native App, I want to create an Axios instance to send headers to the backend with a token taken from AsyncStorage. However, the following Token() always returns an object( Promise ) instead of actual token so that 'Authorization' header is something like [Object object].

import axios from 'react-native-axios'
import AsyncStorage from "@react-native-community/async-storage"

const Token = async () => {
    try {
      await AsyncStorage.getItem("token").then(
        token => token
      );
    } catch (error) {
      return null;
    }
  }

export default axios.create({
      baseURL: 'http://192.168.1.100:8080/api',
      headers: {
        'Authorization': 'Bearer '+ Token(),
        'Content-Type': 'application/json'
      }
}) 

How can I take the actual token and use it in axios instance?

like image 666
Pavindu Avatar asked Jul 15 '19 05:07

Pavindu


2 Answers

Below is how I managed to solve the problem.

As @Prithwee said, I decided to use axios( not react-native-axios) interceptors and set it up in App.js as follows.

import React, {Component} from 'react';
import DrawerNavigator from './Utils/DrawerNavigator'
import {
  createAppContainer
} from 'react-navigation';
import axios from 'axios'
import AsyncStorage from "@react-native-community/async-storage"

axios.defaults.baseURL='http://192.168.1.100:8080/api'

axios.interceptors.request.use(
  async config => {
    const token = await AsyncStorage.getItem('token')
    if (token) {
      config.headers.Authorization = "Bearer "+token
    }
    return config
  },
  error => {
    return Promise.reject(error)
  }
);

const App = createAppContainer(DrawerNavigator);

export default App;
like image 190
Pavindu Avatar answered Oct 27 '22 10:10

Pavindu


A better way would probably be using axios interceptors. this way you can both intercept the request and send your tokens and also when you send refreshed tokens in response you can get that and save them in async storage.

like image 30
Prithwee Das Avatar answered Oct 27 '22 09:10

Prithwee Das