Mani kandan
Mani kandan

Reputation: 261

React Native AsyncStorage getItem returns promise not value

I have a login form and I am able to post the form values. After the successful POST request, I get authentication token returned from the API. I need to save this token for future reference in local storage. For saving this auth token I am using AsyncStorage. I used AsyncStorage.setItem(STORAGE_KEY, responseData.auth_token); setItem method to save the data.

If I console log this by :

console.log(AsyncStorage.setItem(STORAGE_KEY));

it returns as promise object like this

    Promise {_45: 0, _81: 0, _65: null, _54: null}
_45
:
0
_54
:
null
_65
:
"efcc06f00eeec0b529b8"
_81
:
1
__proto__

: Object

how can I get the exact value from the AsyncStorage.getItem method?

This is my fetch method

fetch('http://54.255.201.241/drivers', {
    method: 'POST',
    headers: {
      'Accept': 'application/json',
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({
      first_name: this.state.firstName,
      mobile_number: this.state.mobileNumber,
      vehicle_number: this.state.vehicleNumber,
      vehicle_type_id: 1,
    })
  }).then((response) => response.json()).then((responseData) => {
    if (JSON.stringify(responseData.mobile_number) == (this.state.mobileNumber))
    {
      AsyncStorage.setItem(STORAGE_KEY, responseData.auth_token);
      console.log(AsyncStorage.getItem(STORAGE_KEY));
      this.props.navigator.push({id: 'Otp'})
    }
    else
    {
      Alert.alert("SignUp Failed","Mobile number already taken.")  
    }
  })
  .done();

BTW in documentation they have used await. I tried using that but the pages are not loading.Here with attached the screenshot.enter image description here

Upvotes: 12

Views: 23229

Answers (3)

gildniy
gildniy

Reputation: 3903

This is how I usually manage to get the Value from The Local Storage:

const getItemFromStorage = async () => {
  try {
       await AsyncStorage.getItem('ITEM_NAME', (error: any, result: any) => {
         if (result) {
           console.log(result);
         }else{
           console.log(JSON.stringfy(error));
         }
       });
     } catch (error) {
       console.log(error);
     }
}

Upvotes: 1

Ankit Jayaprakash
Ankit Jayaprakash

Reputation: 1110

You have to call as

getUserToken().then(res => {
    console.log(res);
  });

Since this is an async call.

Upvotes: 9

Abdulaziz Alkharashi
Abdulaziz Alkharashi

Reputation: 1316

using Async/Await :

async _getStorageValue(){
  var value = await AsyncStorage.getItem('ITEM_NAME')
  return value
}

Upvotes: 18

Related Questions