Search code examples
react-nativeasyncstorage

react-native How to get data using AsyncStorage in this.state {}<closed>


I want to use this.state and setState instead of Redux. How can i use AsyncStorage.getItems('user') in this.state?

below is my code, however the code is not working. Do you have any idea? thanks.

class App extends React.Component {

  var value = await ASyncStorage.getItem('user');
  var parsed = JSON.parse(value);

  constructor(props) {
    super(props);
    this.state = {
      name: parsed.name
    };
  }
.
.
.

Solution

  • you made a spell mistake ASyncStorage btw use like this and await is only use like

    try {
      const value = await AsyncStorage.getItem('@MySuperStore:key');
      if (value !== null){
        // We have data!!
        console.log(value);
      }
    } catch (error) {
      // Error retrieving data
    }
    

    here is a code modification

    componentWillMount(){
     var value =  AsyncStorage.getItem('user');
        value.then((e)=>{
          this.setState({
           name: e.name
          })
        })
    }