I'm trying to out some little cart system in my code then but I'm getting only one value in my cart.

For some reason, it seems like going to be an opening array into an array

addCart=()=>{



   var sepet=AsyncStorage.getItem("sepet").then(req=>JSON.parse(req)).then(json=>{

    var sepet=[json];
    sepet.push({isim:this.props.title,fiyat:this.props.fiyat,image:this.props.image});

    AsyncStorage.setItem("sepet",JSON.stringify(sepet));

console.log(sepet)

   });




  }

and then ı'm trying

    export default class aksiyos extends React.Component {

        constructor(props) {
        super(props);
        this.state = {
          ApiTitle: [],
        }
      }


      componentDidMount() {


       var sepet=AsyncStorage.getItem("sepet").then(req=>JSON.parse(req)).then(json=>{

      this.setState({ApiTitle: json });


       });


      }
        render() {
        return (
          <View style={{backgroundColor: "white"}}>
          <ScrollView>{this.state.ApiTitle.map((ids, i)=>

            <Text>{ids.isim}</Text>

    )}
            </ScrollView>
            </View>
        );
      }
     }

but it only shows the last object which I choose

Also I dont know how to remove that objects.

1 Answers

0
Ivan On Best Solutions

You're saving your items as an array, but you're also getting these and putting them inside a new array. Makes sense you only get the last item rendered because this may be the only item that's not inside another array. You can fix this by simply using the spread operator.

const sepets = await AsyncStorage.getItem("sepet")
       .then(req=>JSON.parse(req))
       .then(json => {
           const sepet=[...json]; // <-- If we saved an array, makes sense to spread it in a new array. Otherwise we get [[sepet], sepet]"

           sepet.push({
               isim:this.props.title,
               fiyat:this.props.fiyat,
               image:this.props.image
           });

           AsyncStorage.setItem("sepet",JSON.stringify(sepet)); // <-- save the array

           console.log(sepet)

           return sepet;
        });

Checkout the removeItem() method in the React Native Docs to remove items.