简体   繁体   中英

React Native - Display datas from async AsyncStorage.getItems

Basically, on my app people have to validate when they succeed on a challenge. When they click on the validation button, I save the "key":"value" of the challenge with the function :

async function validate(challenge_nb)
{
 try {
   await AsyncStorage.setItem(challenge_nb, 'OK');
 } catch (error) {
   console.log("error")
 }
}

It works fine.

Now, I would like to get back that data and display it in a list... And I've no idea about how to do that.

I was trying to use that kind of function to get all key/value that I saved :

async function getalldatas()
{
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];
   console.log(value);
  });
});

}); }

But I don't know how to display that in my render() function... Moreover cause it's async

Actually, I would like to do a kind of :

render ( For each key/value : key : value end_foreach )

Thanks a lot !!

You can store it to a state value then have a conditional render, ps never put stuff like this in your render, make it a method of your component:

getAllDatas = () => {
  AsyncStorage.getAllKeys((err, keys) => {
    AsyncStorage.multiGet(keys, (err, stores) => {
      this.setState({ stores });
    });
  });
}

render() {
  return (
    <View>
      {this.state.stores.length && this.state.stores.map(item =>
        <Text>{`${item[0]}: ${item[1}`}</Text>)}
    </View>
  )
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM