0

I am trying to use AsyncStorage to store simple Profile using React Native.

Here is What I have so far for adding Profile, I tried console.log(contact), but showed nothing.

 function AddContact(props) {

  const [FName,setFName] = useState('');
  const [LName,setLName] = useState('');
  const [PNumber,setPNumber] = useState('');

  var contact = {
    firstname : FName,
    lastname : LName,
    phonenumber : PNumber
  };

  const storeContact = async() => {
    try {
      await AsyncStorage.setItem(
        '@MySuperStore:key', JSON.stringify(contact));

    } catch (error) {
    // Error saving data
  }}

For Loading Profile


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

Please help.

2 Answers 2

1

In order to load the data from the Async Storage, your loadContact method should be:

For Loading Profile


  const loadContact = async () => {
    try {
      const value = await AsyncStorage.getItem('@MySuperStore:key');
      const json = JSON.parse(value); // this is how you get back the array stored
      if (json !== null) {
        // We have data!!
        console.log(value);
      }
    } catch (error) {
      // Error retrieving data
    }
  };
Sign up to request clarification or add additional context in comments.

Comments

0

AsyncStorage.getItem() only accept one argument that is key. So you have to pass only argument "key" and it will return your data as string:

const value = await AsyncStorage.getItem('@MySuperStore:key');

Or if you want to use this value as array to display something you have to convert it into json.

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

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.