zahnzy
zahnzy

Reputation: 247

React Native - Retrieve everything in AsyncStorage except keys?

Currently, I am using AsyncStorage.setItem() to push a string key with a stringified JSON object to AsyncStorage. i.e: enter image description here

As I am retrieving everything in AsyncStorage by using getAllKeys() and multiGet(), I am realizing that I only want to access the objects themselves and have no use for the keys.

What would be the most efficient way for me to only access the stringified objects? My current function in which element represents the keys and the values:

importData = () => {
  AsyncStorage.getAllKeys().then(keys => AsyncStorage.multiGet(keys)
    .then((result) => {
      result.map(req => req.forEach((element) => {
        this.setState({ favorites: JSON.parse(element) });
        console.log(this.state.favorites);
      }));
    }));
}

Upvotes: 2

Views: 2351

Answers (1)

Wes
Wes

Reputation: 1945

This should get you all the values except for keys. You're gonna want to JSON.parse() your data if it's in a hierarchy.

  getData = async () => {
    try {
      await AsyncStorage.getAllKeys().then(async keys => {
        await AsyncStorage.multiGet(keys).then(key => {
          key.forEach(data => {
            console.log(data[1]); //values
          });
        });
      });
    } catch (error) {
      Alert.alert("Couldn't load data", error);
    }
  };

Upvotes: 2

Related Questions