sunnylqm / react-native-storage

local storage wrapper for both react-native and browser. Support size controlling, auto expiring, remote data auto syncing and getting batch data in one query.
MIT License
3.02k stars 268 forks source link

i need some help from masters #206

Closed Q8hma closed 5 years ago

Q8hma commented 5 years ago

this is my code cart file:

import {ReactNative,AsyncStorage } from 'react-native';

import Storage from 'react-native-storage';
  const storage = new Storage({
  storageBackend: AsyncStorage,
  defaultExpires: 1000 * 3600 * 24,
  size: 90000,
});
 global.storage = storage;

 export async function removeData(id) {
storage.remove({
  key: 'items',
  id: id
});
return true;
}

 export async function loadAllData() {
storage.getAllDataForKey('items').then(async items => {
return {status:"good",data:items};
}).catch(err => {
    // any exception including data not found
    // goes to catch()
    console.warn(err.message);
    switch (err.name) {
      case 'NotFoundError':
return {status:"error",msg:"Not Found items"};
        break;
      case 'ExpiredError':
return {status:"error",msg:"Expired items"};
        break;
    }
  });
}

 export async function loadData(id) {
storage.load({
    key: 'items',
    id:id
  }).then(async items => {
return {status:"good",data:items};
}).catch(err => {
    // any exception including data not found
    // goes to catch()
    console.warn(err.message);
    switch (err.name) {
      case 'NotFoundError':
return {status:"error",msg:"Not Found items"};
        break;
      case 'ExpiredError':
return {status:"error",msg:"Expired items"};
        break;
    }
  });
}

    export async function addData(item,id) {
        if(!item.count){
          item.count=1;  
        }
storage
  .load({
    key: 'items',
    id:id
  })
  .then(async ret => {
  storage.save({ key: 'items',id:id, data: {...ret,count:(ret.count+1)} });

  }).catch(err => {
  storage.save({ key: 'items',id:id, data: item });

  });
  return true;

}

    export async function addTotalPrice(count,price) {
const totl=count*price;
storage
  .load({
    key: 'totalprice',
  })
  .then(async ret => {
   storage.save({ key: 'totalprice', data: (ret+totl) });

  }).catch(err => {
   storage.save({ key: 'totalprice', data: totl });

  });
  return true;

}

    export async function addStore(store) {
storage
  .load({
    key: 'store',
    id:id
  })
  .then(async ret => {
   storage.save({ key: 'store',id:id, data: {...ret,count:(ret.count+1)} });

  }).catch(err => {
   storage.save({ key: 'store',id:id, data: item });

  });
  return true;

}

    export async function cleanCart() {
storage.clearMap();
storage.remove({
  key: 'totalprice'
});
return true;

}
export default AsyncStorage;

render file :

import React, { Component } from 'react';
import { Container, Content, Text, Header, Body,Item,Badge, Right,Input, Left, Button, Icon, StyleProvider } from 'native-base';
import {AsyncStorage,Alert,ImageBackground,View,Image,Platform,Dimensions,TouchableOpacity,FlatList} from 'react-native';
import { Actions } from 'react-native-router-flux';
import getTheme from '../theme/components';
import material from '../theme/variables/material';
import {removeData,loadAllData,loadData,addData,addTotalPrice,addStore,cleanCart} from '../ultils/cart';
import { Col, Row, Grid } from "react-native-easy-grid";
import Storage from 'react-native-storage';
const isIphoneX =  Platform.OS === "ios" && Dimensions.get("window").height === 812 && Dimensions.get("window").width === 375;
//const loading = require('./logo.png');

export default class info_app extends Component<Props> {
  constructor(Props) {
    super(Props);
    this.state = {
      datas:"",
    }
  }

async fetchAllItems(){
    const data=await loadAllData();
     this.setState({datas:JSON.stringify(data)});
}

async cleanAllItems(){
await cleanCart();
}

async upDateRow(item,id=0) {
await addData(item,id);
}

async  loadRow(id){

    const data= await loadData(id);

     this.setState({datas:JSON.stringify(data)});

  };

  render(){
    return(
<StyleProvider style={getTheme(material)}>
      <Container>

   <Header>
  <Left>
            <Button transparent
            onPress= {() => {Actions.pop(); }}>
              <Icon active style={{color:'#fff'}} name="md-arrow-round-back" />
            </Button>
  </Left>
          <Body>
<Text style={{fontWeight: 'bold',fontSize: 24,color:'#fff'}}> سهفث </Text>
          </Body>
        </Header>
        <Content padder style={{flex: 1,backgroundColor:'#fff'}}>
<Button success fill onPress={()=>{this.upDateRow({id:6,
              name:"text ",
              status:true,
              price:4.000,
              count:1},100)}}><Text>add</Text></Button>
<Button success fill onPress={()=>{this.upDateRow({id:6,
              name:"text ",
              status:true,
              price:4.000,
              count:1},100)}}><Text>update</Text></Button>
<Button success fill  onPress={()=>{this.loadRow(100)}} ><Text>load by id</Text></Button>
<Button success fill onPress={()=>{this.fetchAllItems()}}><Text>load all by ket</Text></Button>
<Button success fill onPress={()=>{this.cleanAllItems()}}><Text>clean</Text></Button>

        <Text>{this.state.datas}</Text>

         </Content>
      </Container>
</StyleProvider>
    );
  }
}

the code not save or load any data

sunnylqm commented 5 years ago

Why use async like this?

.then(async ret => {
Q8hma commented 5 years ago

Why use async like this?

.then(async ret => {

it was test and i forgot to remove it

sunnylqm commented 5 years ago
  1. You are using storage as a global state store. This is completely wrong. Storage is designed to store persistent data, not working as a data tunnel. You should use context, redux, mobx or event emitters. redux + redux-persist should fit your scenario perfectly IMO.
  2. You should add return before storage.xxxx for example:
    export async function loadData(id) {
    + return storage.load({
Q8hma commented 5 years ago

thnx for your help i got little issue on one function

    export async function addData(item,id) {
return storage
  .load({
    key: 'items',
    id:id
  })
  .then(ret => {
  storage.save({ key: 'items',id:id, data: {...ret,count:(ret.count+1)} });
return {status:"good",msg:"update"};
  }).catch(err => {
  storage.save({ key: 'items',id:id, data: item });
return {status:"good",msg:"new"};
  });
}

it not add 1 it add 2 , every time i call it it count+2

sunnylqm commented 5 years ago

I did not see how you retrieved the updated data (btw, data are already plural so no datas). Besides, your code style and indentation are really bad, which is easy to make mistakes and difficult for other people to review. You really need to use prettier and eslint to clean up your code.

Q8hma commented 5 years ago

thnx bro , got the error 👍 :) ... i call the add 2 time

i want to ask you how to donation ??

sunnylqm commented 5 years ago

Thanks for your kindness. Currently it's too troublesome to accept donation.