React Native - Return all JSON data in AsyncStorage?

zahnzy picture zahnzy · Jan 10, 2018 · Viewed 10.1k times · Source

In my React Native app's AsyncStorage, I have multiple JSON objects, each with a unique key id like so:

 '62834456':
 data: { "foo": "bar",
 "nicknames": [ "grizz", "example" ],
 ... and so on }

They have been pushed into AsyncStorage stringified. I'm trying to retrieve every object by their id, and push both the id and its' JSON data into the component's state. I have this so far:

// for every key in async storage, push to favorites in state
importData = (id) => {
  for (id in AsyncStorage) {
    return AsyncStorage.getItem(id)
      .then(req => JSON.parse(req))
      .then(json => console.log(json))
      .catch(error => console.log('error!'));
  }
}

When console.logging 'json' in the above function, the result is null. How can I properly access all JSON objects in my AsyncStorage?

FINAL EDIT

Using your code example and removing JSON.parse (so simply console.logging req) returns this: enter image description here

It appears this is happening because for some reason .forEach is returning the first string in the array, the array itself, then the second string.

Answer

H. Tugkan Kibar picture H. Tugkan Kibar · Jan 10, 2018

In order to get all AsyncStorage keys, you need to call AsyncStorage.getAllKeys(). In order to speed things up, you should also use AsyncStorage.multiGet() By doing that your code becomes;

importData = async () => {
  try {
    const keys = await AsyncStorage.getAllKeys();
    const result = await AsyncStorage.multiGet(keys);

    return result.map(req => JSON.parse(req)).forEach(console.log);
  } catch (error) {
    console.error(error)
  }
}