Home React Native - Return all JSON data in AsyncStorage?
Reply: 1

React Native - Return all JSON data in AsyncStorage?

zahnzy Published in 2018-01-10 19:10:16Z

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

 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?


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

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.

H. Tugkan Kibar
H. Tugkan Kibar Reply to 2018-01-10 20:35:52Z

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 = (id) => {
  AsyncStorage.getAllKeys.then((keys) => {
    return AsyncStorage.multiGet(keys)
      .then((result) => {
        result.map(req => JSON.parse(req)).forEach(console.log);
You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.305313 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO