简体   繁体   中英

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

here I have pasted code which is written class component for mobx state management and i am calling it to another file,the thing is I have above 450 api responses and it need to store locally so i have tried it but i am not getting any value nor the data stored in database pls help me out thanks in advance..

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() returns a promise, not the value. So, just add a then block after the line AsyncStorage.getItem('ACCESS_TOKEN');. It would be like this

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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