1
votes

So I am using the AsyncStorage in react native right now to store the api key to make a request using axios. When I call AsyncStorage to get an item I get [Object Object] instead of the key.

I tried async await function to resolve the promise to get the value but I am still getting the promise instead of the value that is in the promise. I also tried to return the value with a then and return the value.

import {AsyncStorage} from 'react-native';

class APIToken {
    constructor(){}
    async get(){
        try {
            const token = await AsyncStorage.getItem('api_token');
            if (token !== null) {
              // We have data!!
              console.log(token);
              return token
            }
          } catch (error) {
            // Error retrieving data
          }
          //return null
    }
    async set(token){
        try {
            await AsyncStorage.setItem('api_token', token);
            return token
          } catch (error) {
            // Error saving data
          }
          //return null
    }
}

export default APIToken

const key = async function() {
    const k = await (new APIToken()).get()
    return k
  }


const api = axios.create({
    baseURL: Config.API_URL_V1,
    headers: {
        'Content-Type': 'application/json',
        'Authorization': 'Bearer ' + key(),
        'Cache-Control': 'no-cache'
    }
  });
1

1 Answers

-1
votes

The AsyncStorage saves data as string. Have you tried calling JSON.stringify on the key before saving and JSON.parse after retrieving the value from the storage?