-2

I've been looking for answers on stack overflow but so far nothing is working. I'm using this function(below) to retrieve a simple array since i want to show its contents in the return() function.

_retrieveData = async () => {
  try {
    const value = await AsyncStorage.getItem('FavouritesArray');
    if (value !== null) {
      // We have data!!
      console.log(value);
    }
  } catch (error) {
    // Error retrieving data
  }
};

The code does work and it logs the array I want (["Rose","Mojito"]) but i can't figure out how to get the array outside the _retrieveData() function. I've tried returning it (returns a promise) as well as putting it in a global variable and then returning it, but that also just return a promise object.

How do I extract the populated array from this async function?

Samuli Hakoniemi
  • 18,740
  • 1
  • 61
  • 74
AWE
  • 64
  • 4
  • 14
  • Does this answer your question? [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Jared Smith Sep 25 '20 at 11:19

1 Answers1

1

You can store and retrieve your data like this with AsyncStorage:

  const storeData = async (key, value) => {
    try {
      await AsyncStorage.setItem(key, value); 
    } catch (error) {
      console.log(error);
    }
  };

  const getData = async key => {
    try {
      const data = await AsyncStorage.getItem(key);
      if (data !== null) {
        console.log(data);
        return data;
      }
    } catch (error) {
      console.log(error);
    }
  };

then call getData with the key name like you stored your array wherever you want and set the key to a state array.

  await getData("yourarraykey") 
    .then((data) => data)
    .then((value) => this.setState({ yourarraystate: value }))
    .catch((err) => console.log("AsyncStorageErr: " + err));

after that in this.state.yourarraystate the value of your fetched array will be available.

~Faded

yesIamFaded
  • 1,970
  • 2
  • 20
  • 45