反应本机异步存储设置项功能 [英] React Native Async Storage set item function

查看:57
本文介绍了反应本机异步存储设置项功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在商品列表应用中使用了异步存储.我面临的问题是,直到我输入第二个项目,我的第一个项目才会存储在异步中.我正在使用react hooks来保存对象数组例如,如果我将项目输入为1)苹果2)香蕉那么只有苹果会保存在异步中,而香蕉要等到我输入第三项后才能保存.

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()
      }, [])

在提交文本框时调用的additems功能内部调用saveData函数

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

推荐答案

您忘记等待清除数据.它在本质上也是异步的.

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

等待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.

了解更多: https://react-native-async-storage.github.io/async-storage/docs/api#clear

:-D

这篇关于反应本机异步存储设置项功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆