0

I have a problem that I do not know how to solve...

I have an api token saved in AsyncStorage, and when I want do fetch to rest I need this api token, but I do not know how to do it.

I have file Functions.js with AsyncStorage functions.

async retrieveItem(key) {
  try {
    const retrievedItem =  await AsyncStorage.getItem(key);
    const item = JSON.parse(retrievedItem);
    return item;
  } catch (error) {
    console.warn(error.message);
  }
},
getApiToken: function(){
   try {
        return Functions.retrieveItem('api_token');
      } catch (error) {
        console.warn(error.message);
      }
    },

File with fetch functions. (Api.js)

I tested with an asynchronous function, but not found...

async get(url) {

    try {
        var api = await Functions.getApiToken();

        if (!api)
            api = "";

        let opt = {
            method: 'get',
            headers: new Headers({
                'Content-Type': 'application/x-www-form-urlencoded'
            }),
        };

        return fetch(baseUrl + url + api, opt);
    } catch (error){
        console.warn(error);
    }       

},

When I did the fetch function, it worked for me without problems

And the screen file Home.js

componentDidMount() {

  Api.get('home').then( response => {
    this.setState({
        profiles: response.profiles,
    });
  });
}

1 Answer 1

2

Please modify your Functions.js code a bit -

async retrieveItem(key) {
  try {
    const retrievedItem = await AsyncStorage.getItem(key);
    const item = JSON.parse(retrievedItem);
    return item;
  } catch (error) {
    console.warn(error.message);
  }
},

async getApiToken{
  try {
    let token = await retrieveItem('api_token');
    return token;
  } catch (error) {
    console.warn(error.message);
  }
}

Hope this helps you!

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.