问题
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
回答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
回答2:
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.
来源:https://stackoverflow.com/questions/64669211/react-native-async-storage-set-item-function