Search code examples
react-nativeasyncstorage

AsyncStorage getItem() doesn't return null ever


I'm using AsyncStorage in a React Native app and (if I understand the docs right) the getItem() method is supposed to return null if nothing has been stored for a given key.

From the documentation:

getItem() ... Returns: Promise resolving with a string value, if an entry exists for a given key, or null otherwise."

However, whenever I fetch data for a new key, it is never null. My getItem function is in a useEffect hook to try and load the data before the first render.

useEffect(() => {
  getData();
}, []);

 const storeData = async () => {
    try {
      setMyInfo({...})
      const jsonInfo = JSON.stringify({myInfo})
      await AsyncStorage.setItem(storage_Key, jsonInfo)
      alert('Data successfully saved')
    } catch (e) {
      alert('Failed to save the data to the storage')
    }
  }

const getData = async () => {
  try {
    let data = await AsyncStorage.getItem(storage_Key);
    if (data !== null) {
      setMyInfo(JSON.parse(data));
    } else {
      alert("test");
    }
  } catch (e) {
    alert("Failed to fetch the data from storage");
  }
};

myInfo, the variable is a JSON object and it actually seems to fill all the values with "Useless Placeholder". Like this:

myInfo = {
  value1: "Useless Placeholder",
  value2: "Useless Placeholder",
};

My current solution:

Even though the getItem() function is inside of useEffect hook, the myInfo variable is undefined for a half second at the beginning. So I have a ternary operator to display the values if the variable is defined.

<Text>{typeof myInfo === 'undefined' ? '' : myInfo.value1}</Text>

It will throw a 'myInfo is undefined' error if I just attempt to display myInfo.value1. But, this way, even before any data has been stored for the specified key, the value "Useless Placeholder" will appear when opening this page.

This works for me for now, but some guidance on how to actually work with asynstorage here would be appreciated.


Solution

  • I figured out what was going on.

    Turns out that when storing the data, the useState variable was not being set to the new values. I found that if I attempted to trigger the storeData function twice that it would actually save the data properly. So, to fix the issue, I changed my storeData function to the following:

     const storeData = async () => {
        try {
          const jsonRnfo = JSON.stringify({
             value1: value,
             value2: value, ....
          })
          await AsyncStorage.setItem(storage_Key, jsonInfo)
          alert('Data successfully saved')
        } catch (e) {
          alert('Failed to save the data to the storage')
        }
      }
    

    Instead of using AsyncStorage.setItem() to store the data from the useState, I just built a new JSON object in my storeData function. The useState is still used in the app for frontend purposes.