Search code examples
reactjsreact-nativeasync-awaitasyncstorage

React Native Async Storage set item function


I am using async storage in my items listing app. The problem i am facing is that, my first item does not get stored in the async till i enter the second item. i am saving array of objects with the help of react hooks E.g if I enter items as 1)Apples 2)Bananas then only apples will get saved in the async while bananas will not be saved until i enter the third item.

const [getWant, setwant] = useState([]);

const saveData = async () => {
      AsyncStorage.clear()
       try {
        await AsyncStorage.setItem("@pantry102", JSON.stringify(getWant))
         console.log(getWant)
         alert('Data successfully saved')
       } catch (e) {
         alert('Failed to save the data to the storage')
       }
     }
const readData = async () => {
        try {
          const userData= await AsyncStorage.getItem("@pantry102")
          const userData2 = JSON.parse(userData)
          if (userData2 !== null) {
            console.log(userData2)
            setwant(userData2)
            
          }
        } catch (e) {
        alert('Failed to fetch the data from storage')
        }
      }
useEffect(() => {
      readData()
      }, [])

the saveData function gets called inside the additems fucntion which is envoked when textbox is submitted


Solution

  • You forgot to await to clear data. It is async in nature too.

    await AsyncStorage.clear()

    const saveData = async () => {
      try {
        await AsyncStorage.clear();
        await AsyncStorage.setItem("@pantry102", JSON.stringify(getWant));
        console.log(getWant);
        alert("Data successfully saved");
      } catch (e) {
        alert("Failed to save the data to the storage");
      }
    };
    

    I will suggest, just override it. No need to clear.

    Read More: https://react-native-async-storage.github.io/async-storage/docs/api#clear

    :-D