Search code examples
javascriptreact-nativeasynchronousasync-awaitasyncstorage

AsyncStorage returns Promise when retrieving item


Explanation

I am trying to use AsyncStorage in order to save a Token during Login. The token is recieved from my backend as a response after the user presses the Login button. After a successful login the screen goes to the ProfileScreen where I try to retrieve the saved token.

Problem

When I try to retrieve the item in the ProfileScreen and console log it I seem to get a Promise object filled with other objects and inside there I can see my value. How do I recieve the value ? (or should I say how do I fulfill the promise :) )

Code

Utilities/AsyncStorage.js(Here I have my helper functions for store and retrieve item)

const keys = {
jwtKey: 'jwtKey'
}

const storeItem = async (key, item) => {
  try {
    var jsonOfItem = await AsyncStorage.setItem(key, JSON.stringify(item));
    console.log('Item Stored !');
    return jsonOfItem;
  } catch (error) {
    console.log(error.message);
  }
};

const retrieveItem = async key => {
  try {
    const retrievedItem = await AsyncStorage.getItem(key);
    const item = JSON.parse(retrievedItem);
    console.log('Item Retrieved !');
    return item;
  } catch (error) {
    console.log(error.message);
  }
  return;
};

LoginScreen.js(Here, after login button is pressed I recieve a response from my backend with Token)

const LoginScreen = ({componentId}) => {
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const loginPressed = async () => {
    await axios
      .post('localhost', {
        email,
        password,
      })
      .then(function(res) {
        console.log(res);
        storeItem(keys.jwtKey, res.data.token);
        push(componentID, views.profileScreen());
      })
      .catch(function(error) {
        console.log(error);
      });
  };

ProfileScreen.js(On this screen I try to retrieve the token because I will be using it)

const ProfileScreen = ({componentID}) => {
let testingAsync = retrieveItem(keys.jwtKey);
console.log(testingAsync);

The console log gives me promise object filled with other objects.

Promise{_40:0, _65:0 , _55:null, _72:null}

And inside the _55 I can find the value of the token.


Solution

  • Thank you for your comments! I solved it by using .then() in my ProfileScreen as @Bergi mentioned in his comment. Then after I recieved the second comment I made an async&await function in my ProfileScreen inside a useEffect to prevent it from repeating itself which solved the issue for me!