quad clipse
quad clipse

Reputation: 5

How to use AsyncStorage to store array in React Native

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.

Upvotes: 0

Views: 2057

Answers (2)

Saadi
Saadi

Reputation: 1294

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

Upvotes: 1

Kishan Bharda
Kishan Bharda

Reputation: 5700

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

Upvotes: 0

Related Questions