12

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?

0

3 Answers 3

31

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;
2
  • Have you get null value for await AsyncStorage.getItem('token') anytime? I am use the same code like you but while using application sometimes await AsyncStorage.getItem('token') returns null token. Feb 7, 2020 at 10:19
  • Maybe you haven't set the token first using AsyncStorage.setItem("token",value)?
    – Pavindu
    Feb 8, 2020 at 5:10
4

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.

0

By using @Pavindu's solution, I've implemented this solution that could be implemented all throughout any components needed.

base.js

import axios from 'axios'
import { AsyncStorage } from 'react-native'

axios.defaults.baseURL = 'http://yourAPIaddress.com'

const apiInstance = axios.create()

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

export default apiInstance

Your component

import apiInstance from '../api/base'


export default () => {
    const [stores, setStores] = useState([])
    
    use Effect(() => {
        apiInstance
            .get('../api/stores')
            .then(res => {
                setStores(res.data)
            })
            .catch(err => {
                alert(err)
                console.log(err)
            })
    },    [])
    
    return [stores]
}
0

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.