简体   繁体   中英

How to use asyncstorage in ReactNative

I made localstorage in ReactJS that works well.
But I want to use this code to React-native.
I am confused how I can apply to
This code is of ReactJs.

...
  componentWillMount(){
    const contactData = localStorage.contactData;
    if(contactData){
      this.setState({
        contactData:JSON.parse(contactData)
      })
    }
  }
...
...
  componentWillMount(){
    const contactData = localStorage.contactData;
    if(contactData){
      this.setState({
        contactData:JSON.parse(contactData)
      })
    }
  }
...

I read this " https://facebook.github.io/react-native/docs/asyncstorage.html "
But I don't understand well.

For the React-native storage, you have to use the AsyncStorage. Above Code in react-native will become.

...
async componentWillMount(){
const contactData = await AsyncStorage.getItem('contactData');
if(contactData){
  this.setState({
    contactData:JSON.parse(contactData)
  })
}
}
...
...
async componentWillMount(){
const contactData = localStorage.getItem('contactData');
if(contactData){
  this.setState({
    contactData:JSON.parse(contactData)
  })
}
}
...

You can either use the async-await or then/catch promise for handling the data.

    this.retrieveItem(goalCategory).then((goals) => {
              //this callback is executed when your Promise is resolved
              }).catch((error) => {
              //this callback is executed when your Promise is rejected
              console.log('Promise is rejected with error: ' + error);
              }); 

//the functionality of the retrieveItem is shown below
async retrieveItem(key) {
    try {
      const retrievedItem =  await AsyncStorage.getItem(key);
      const item = JSON.parse(retrievedItem);
      return item;
    } catch (error) {
      console.log(error.message);
    }
    return
  }

Save to AsyncStorage

const saveUserId = async userId => {
  try {
    await AsyncStorage.setItem('userId', userId);
  } catch (error) {
    // Error retrieving data
    console.log(error.message);
  }
};

Retrieve a value from AsyncStorage

    const getUserId = async () => {
          try {
            const uid = await AsyncStorage.getItem('userId');
             console.log(uid);
              } catch (error) {
                // Error retrieving data
                console.log(error.message);
              }
            };

Delete from AsyncStorage

const deleteUserId = async () => {
  try {
    await AsyncStorage.removeItem('userId');
  } catch (error) {
    // Error retrieving data
    console.log(error.message);
  }
}

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