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:
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.
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)
}
}
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")
}
}
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With