trying to save to save data in asycstorage but unable to it so

Viewed 82

here i have pasted my whole code , here i have api which has 400 + responses and it need to store in asyncstorage like it need to store in local database this api is limited,and people also suggesting me to write this in async await but i am not aware of async await could u pls edit the code and help me out and the important thing is I am using mobx state tree to access this code in another file. thanks in advance.

import {makeAutoObservable, action} from 'mobx';
import {Dimensions, Platform} from 'react-native';
import AsyncStorage from '@react-native-async-storage/async-storage';
const {width, height} = Dimensions.get('window');
import {encode} from 'base-64';
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);
  }

  // searchFilter = text => {
  //   if (text) {
  //     // setIsfilterdData(ProductStore.productData);
  //     const fData = this.productData;
  //     const newData = fData.filter(item => {
  //       const itemData =
  //         item.product || item.id
  //           ? item.product.toUpperCase() || item.id
  //           : ''.toUpperCase();
  //       const textData = text.toUpperCase();
  //       return itemData.indexOf(textData) > -1;
  //     });
  //     this.filterdData = newData;
  //     this.search = text;
  //   } else {
  //     this.isFlatlistRender = true;
  //     this.search = text;
  //   }
  // };
  
  getproductData = async () => {
    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('dataKey', JSON.stringify(responseJson));

        // retrieving data whenever you need from local storage
        AsyncStorage.getItem('dataKey')
          .then(responseJson => {
            if (responseJson) {
              let ourData = JSON.parse(responseJson);
              console.log('ourData >>>>> ', ourData);
              this.productData = ourData;
              this.isProductLoading = 'done';
            }
          })
          .catch(err => console.log('error >>>>> ', err));
        // this.productData = ourData;
        // this.isProductLoading = 'done';
      })
      .catch(error => {
        console.error(error);
        this.isProductLoading = 'error';
      });
  };
}
export default new ProductStore();
1 Answers

if you want to use mobx i guess there is middleware to save the state in localStorage like Redux-Persist on redux

but if you want to use AsyncStorage only then u can do this.

the save one its already correct.

this one is get

//save this code on helper or something
export const getItem = async ()=>{
   try{
       const data = await AsyncStorage.getItem('dataKey');
       if(!data) throw new Error("Data doesn't exist yet")
       return [true,JSON.parse(data)];
       //first array is boolean to check if it success or not
       //2nd array is data or error message (if false)
    } catch (e){
       return [false,e.message];
    }   
}

and then you call it inside a didmount or useEffect and save it to state

import {getItem} from './FileLocation';

//for class component
async ComponentDidMount(){
   const [success,data] = await getItem();
   if(success){
      this.setState({data})
   } else{
      Alert.alert('Error',data)
   }
}

//functional

const [data,setData] = React.useState([]);

const FetchItem = async ()=>{
   const [success,data] = await getItem();
    if(success){
      setData(data)
   } else{
      Alert.alert('Error',data)
   }
}

React.useEffect(()=>{
   FetchItem();
},[])

Related