0

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

2
  • based on what output do you say that the item doesn't get saved? Commented Nov 3, 2020 at 23:13
  • i used the console.log it shows empty array on first save and on second save it contains the first item. Also when i reload the app to check the old saved data only the first item gets displayed when both item should be. Here is my snack expo link snack.expo.io/@moeez71/7f7d44 you can test it yourself Commented Nov 4, 2020 at 4:45

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

1 Comment

yeah i fixed it using await in my AddItem function with await setWant(). Thanks though :)
0

There is an open source library react-native-easy-app, which wraps the use of AsyncStorage, through which you can access any data in AsncStorage synchronously, maybe it can solve your problem, there is sample program below, maybe you can refer to it. code.

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.