How to get multi keys from AsyncStorage and then add these keys into an array?

Viewed 2591

I wanna get multi keys from AsyncStorage and add these keys into an array.

AsyncStorage.multiGet(
 ['key1',
  'key2',
  'key3',
  'key4',
  'key5',]
).then(() => {

})
2 Answers

You can use map function for this:

AsyncStorage.getAllKeys((err, keys) => {
  AsyncStorage.multiGet(keys, (err, stores) => {
    stores.map((result, i, store) => {
      // get at each store's key/value so you can work with it
      let key = store[i][0];
      let value = store[i][1];
    });
  });
});

this is an example from doc here AsyncStorage

async getKeysData(keys){
  const stores = await AsyncStorage.multiGet(keys);
  return stores.map(([key, value]) => ({[key]: value}))
}

getKeysData(['key1', 'key2', 'key3'])
 .then((response)=>{ console.log(response)})
 
 /*
 Respose will be in below form 
 response = [
  {key1: 'DATAOF key1'},
  {key2: {"DATA OF KEY2"}}
  {key3: 'DATAOF key1'}
*/
 

Related