Search code examples
xcodereact-nativeasyncstorage

AsyncStorage - error (React Native)


I have a problem with persisting user's data in a react-native application I am currently working on with my team. We have an app with a list of events and when you click on an event, it opens up the event details page and shows a menu to choose yes/no/maybe (attendance menu) which the user can toggle to select whether or not they are attending the event. Our code looks like this:

import React from 'react';
import { AsyncStorage, Text, View, StyleSheet, Picker } from 'react-native';

export class PickerMenu extends React.Component {
    state = { choice: '' }

   componentDidMount = () => AsyncStorage.getItem('choice').then((value) => this.setState({ 'choice': value }))

   setName = (value) => {
     AsyncStorage.setItem('choice', value);
     this.setState({ 'choice': value });
   }
   render() {
     return (
       <View>
         <Picker selectedValue = {this.state.choice} onValueChange = {this.setName} itemStyle = {styles.item}>
           <Picker.Item label = "Yes" value = "yes" />
           <Picker.Item label = "Maybe" value = "maybe" />
           <Picker.Item label = "No" value = "no" />
         </Picker>
       </View>
     );
   }
}

We are running the build on Xcode. We want the user's choice to still be present after the page has been refreshed or the app has closed - this works HOWEVER,the choice that the user has selected, stays the same for every event. E.g. if they select 'Maybe' for event 1, the selection 'maybe' is highlighted for every other event in our app.

We had an idea of grabbing unique event IDs and implementing this into the AsyncStorage function but we are unsure of how to do this.

Any help will be great and much appreciated - thank-you!


Solution

  • In this case you need to use the async/await to store at the async storage like this:

    setName = async (value) => {
       await AsyncStorage.setItem('choice', value);
       this.setState({ 'choice': value });
    }
    

    Hope i have helped!

    Some useful links for you:

    https://facebook.github.io/react-native/docs/asyncstorage.html