1

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.

3 Answers 3

4

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.

Sign up to request clarification or add additional context in comments.

Comments

1
    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
  }

Comments

0

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);
  }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.