Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Native - Return all JSON data in AsyncStorage?

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.

like image 624
zahnzy Avatar asked Jan 10 '18 19:01

zahnzy


3 Answers

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)
  }
}
like image 107
H. Tugkan Kibar Avatar answered Nov 04 '22 03:11

H. Tugkan Kibar


here is a more elegant way to get all items using async/await functions

const fetchAllItems = async () => {
    try {
        const keys = await AsyncStorage.getAllKeys()
        const items = await AsyncStorage.multiGet(keys)

        return items
    } catch (error) {
        console.log(error, "problemo")
    }
}
like image 38
georgekpc Avatar answered Nov 04 '22 03:11

georgekpc


May be, little straight forward using promises.

import { AsyncStorage } from 'react-native';

  AsyncStorage.getAllKeys()
    .then((keys)=> AsyncStorage.multiGet(keys)
                    .then((data) => console.log(data)));

Cheers!

like image 3
Ram Grandhi Avatar answered Nov 04 '22 03:11

Ram Grandhi