Search code examples
react-nativeasync-awaitasyncstorage

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.


Solution

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