skip to Main Content

I am having some trouble trying to get an Item from AsyncStorage in React Native without transform it into an async function and use await.

Based on this answer, I was trying to do something like this:

const getItem = (key) => {  
  AsyncStorage.getItem("access_token").then(value=>{
    console.log(value, " first")
    return value
  });
};

const test = () => {
  const teste = getItem()
  console.log(teste, " final"); 
}

The crazy part is when a call test function (on a onPress event, for instance), I get the following printed:

LOG  undefined  final
LOG  00b3ceb97ae8d9357abd1065f50be408a9389f23  first

The final log, which should be displayed at the end, is printed first and is undefined.

Edit:

Another try:

const getItem = (key) => {  
  const value = AsyncStorage.getItem("access_token").then(value=>{
    console.log(value, " first")
    return value
  });

  console.log(value, " second")

};

This is the log:

LOG  {"_h": 0, "_i": 0, "_j": null, "_k": null}  second
LOG  00b3ceb97ae8d9357abd1065f50be408a9389f23  first

Am I missing something here? Is it possible to use "then" to get data with AsyncStorage lib without the async await mechanism?

"react-native": "0.73.6" and "@react-native-async-storage/async-storage": "^1.23.1",

2

Answers


  1. Chosen as BEST ANSWER

    I was having a total misunderstanding of the use of "then". I thought that with it I did not have to wait and use the response outside.

    const getItem = (key) => {  
      const value = AsyncStorage.getItem("access_token").then(value=>{
        // here i can use it without wait. To set a useState, for instance.
        return value
      });
      console.log(value) // this is not gonna work.
    };
    

    Thanks, @derpirscher and @slebetman


  2. In your case I suggest to return Promise from getItem and use then after:

    const getItem = (key) => {  
      return AsyncStorage.getItem("access_token").then(value => {
        console.log(value, " first");
        return value
      });
    };
    
    const test = () => {
      getItem().then((value) => console.log(value, " final"));
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search