I getting an error while I try to put data for my cart system.
I can put data when I try [json];
but I couldn't when I change it to[...json];
[json];
is giving me the last item that I put but I need all of them
addCart=()=>{
const sepets = AsyncStorage.getItem("sepet")
.then(req => {
const json = JSON.parse(req);
const sepet=[...json];
sepet.push({isim:this.props.title,fiyat:this.props.fiyat,image:this.props.image});
AsyncStorage.setItem("sepet",JSON.stringify(sepet));
});
}
the error that gives me "Possible Unhandled Promise Rejection (id: 0): TypeError: Invalid attempt to spread non-iterable instance TypeError: Invalid attempt to spread non-iterable instance at _nonIterableSpread "
I'm removing items like this 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 });
});
}
removeCart=()=>{
AsyncStorage.removeItem("sepet")
}
render() {
return (
<View style={{backgroundColor: "white"}}>
<ScrollView>{this.state.ApiTitle.map((ids, i)=>
<Text>{ids.isim}</Text>
)}
</ScrollView>
<Text onPress={this.removeCart}>Buton</Text>
</View>
);
}
}
`
You don't need the extra .then()
when you parse your data. You need to also check for null, after removing the items, getItem will return null.
const sepets = AsyncStorage.getItem("sepet")
.then(req => {
let json = JSON.parse(req);
if (!json) {
json = [];
}
const 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)
});
In your render validate ApiTitle
before using it.
render() {
const items = this.state.ApiTitle || [];
return (
<View style={{ backgroundColor: "white" }}>
<ScrollView>{items.map((ids, i) =>
<Text>{ids.isim}</Text>
)}
</ScrollView>
<Text onPress={this.removeCart}>Buton</Text>
</View>
);
}