Cookie
Cookie

Reputation: 362

React native - AsyncStorage, wait and sync

I'm use AsyncStorage, but I think I do not use correcly...

file functions.js

import { AsyncStorage } from 'react-native';

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

export default Functions;

File home.js

import Functions from 'Constants/functions';

export default class Home extends Component {


  constructor(props) {
    super(props);

    product = Functions.retrieveItem('products');
   console.warn(product);
  }
}

console.warn(product) returned

{"_40":0,_65":1,"_55":null,"_72":null}

I believe that this happens because I receive the object before it has been processed. Because if I put a console.warn before the return of the retrieveItem function it shows the object well...

Upvotes: 0

Views: 1135

Answers (1)

UXDart
UXDart

Reputation: 2620

is a Promise so... you need to use

Functions.retrieveItem('products').then((res) => { //do something with res });

Upvotes: 2

Related Questions