繁体   English   中英

试图将 api 响应存储在异步存储中,但我无法存储它

[英]trying to store api responses in asyncstorage but I am unable to store it

在这里,我粘贴了编写 class 组件的代码,用于 mobx state 管理,我将其调用到另一个文件,问题是我有超过 450 个 api 响应,所以我不需要在本地获取任何值,但我已经尝试过它在本地存储响应也不是存储在数据库中的数据请帮助我提前谢谢..

class ProductStore {
  constructor() {
    makeAutoObservable(this);
  }

  screenWidth = width;

  screenHeight = height;

  headerHeight = 0;

  isiOS = Platform.OS === 'ios';

  isAndroid = Platform.OS === 'android';

  isProductLoading = 'pending';

  productData = [];

  filterdData = [];

  search = '';

  isFlatlistRender = false;

  setFields(eName, data) {
    this[eName] = data;
    console.log(eName, data);
  }

  
  getproductData = () => {
    if (this.isProductLoading == 'loading') {
      return true;
    }
    this.isProductLoading = 'loading';
    this.productData = [];

    let headers = new Headers();
    headers.set(
      'Authorization',
      'Basic ' + encode('username:password'),
    );

    fetch('some_url', {
      method: 'GET',
      headers: headers,
    })
      .then(response => response.json())
      .then(responseJson => {
        console.log('.....', responseJson);
        AsyncStorage.setItem(
          'ACCESS_TOKEN',
          JSON.stringify(responseJson),
          err => {
            if (err) {
              console.log('an error');
              throw err;
            }
            console.log('success');
          },
        ).catch(err => {
          console.log('error is: ' + err);
        });
        try {
          const value = AsyncStorage.getItem('ACCESS_TOKEN');
          if (value !== null) {
            console.log(JSON.parse(value));
          }
        } catch (error) {}
        this.productData = responseJson;
        this.isProductLoading = 'done';
      })
      .catch(error => {
        console.error(error);
        this.isProductLoading = 'error';
      });
  };
}
export default new ProductStore();

AsyncStorage.getItem() 返回 promise,而不是值。 因此,只需在AsyncStorage.getItem('ACCESS_TOKEN');行之后添加一个then . 会是这样

AsyncStorage.getItem('ACCESS_TOKEN').then(value => {
          if (value !== null) {
            console.log(JSON.parse(value));
          }
}).catch(err => console.error(err));

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM