
Hoy voy a ensenar como hacer un carrito de productos.
This containt show how to build food cart .
AsyncStorage
AsyncStorage es un sistema de almacenamiento de clave-valor no cifrado, asíncrono, persistente y global para la aplicación. Debe usarse en lugar de LocalStorage.
npm install --save @react-native-community/async-storage
Run android
react-native run-android
Clean cache
react-native start --reset-cache
Button in Food.js
import
// import AsyncStorage
import AsyncStorage from '@react-native-community/async-storage';
// import icons
import Icon from 'react-native-vector-icons/Ionicons';
Button
<TouchableOpacity
onPress={()=>this.onClickAddCart(item)}
style={{
width:(width/2)-40,
backgroundColor:'#33c37d',
flexDirection:'row',
alignItems:'center',
justifyContent:"center",
borderRadius:5,
padding:4
}}>
<Text style={{fontSize:18, color:"white", fontWeight:"bold"}}>Add Cart</Text>
<View style={{width:10}} />
<Icon name="ios-add-circle" size={30} color={"white"} />
</TouchableOpacity>
Function for Button
onClickAddCart(data){
const itemcart = {
food: data,
quantity: 1,
price: data.price
}
AsyncStorage.getItem('cart').then((datacart)=>{
if (datacart !== null) {
// We have data!!
const cart = JSON.parse(datacart)
cart.push(itemcart)
AsyncStorage.setItem('cart',JSON.stringify(cart));
}
else{
const cart = []
cart.push(itemcart)
AsyncStorage.setItem('cart',JSON.stringify(cart));
}
alert("Add Cart")
})
.catch((err)=>{
alert(err)
})
}
Cart
import
import React, { Component } from 'react';
import { Text, View, TextInput, Image, TouchableOpacity, StyleSheet, Dimensions } from 'react-native';
var { width } = Dimensions.get("window")
// import icons
import Icon from 'react-native-vector-icons/Ionicons';
render
render() {
return (
<View style={{flex:1,alignItems: 'center', justifyContent: 'center'}}>
<View style={{height:20}} />
<Text style={{fontSize:28, color:"gray"}}>Cart food</Text>
<View style={{height:10}} />
<View style={{flex:1}}>
<View style={{width:width-20,margin:10,backgroundColor:'transparent', flexDirection:'row', borderBottomWidth:2, borderColor:"#cccccc", paddingBottom:10}}>
<Image resizeMode={"contain"} style={{width:width/3,height:width/3}} source={{uri: "http://tutofox.com/foodapp/food/pizza/pizza-1.png"}} />
<View style={{flex:1, backgroundColor:'transparent', padding:10, justifyContent:"space-between"}}>
<View>
<Text style={{fontWeight:"bold", fontSize:20}}>Titulo de producto</Text>
<Text>Descripcion de food</Text>
</View>
<View style={{flexDirection:'row',justifyContent:'space-between'}}>
<Text style={{fontWeight:'bold',color:"#9fd236",fontSize:20}}>$565</Text>
<View style={{flexDirection:'row', alignItems:'center'}}>
<TouchableOpacity>
<Icon name="ios-remove-circle" size={30} color={"#9fd236"} />
</TouchableOpacity>
<Text style={{paddingHorizontal:8, fontWeight:'bold'}}>5</Text>
<TouchableOpacity>
<Icon name="ios-add-circle" size={30} color={"#9fd236"} />
</TouchableOpacity>
</View>
</View>
</View>
</View>
</View>
<View style={{height:20}} />
<TouchableOpacity style={{
backgroundColor:"#9fd236",
width:width-40,
alignItems:'center',
padding:10,
borderRadius:5
}}>
<Text style={{
fontSize:24,
fontWeight:"bold",
color:'white'
}}>
CHECKOUT
</Text>
</TouchableOpacity>
<View style={{height:20}} />
</View>
);
}
Cart Part 2 : Render cart from asyncstorage
import
import AsyncStorage from '@react-native-community/async-storage';
state
constructor(props) {
super(props);
this.state = {
dataCart:[],
};
}
componentDidMount
componentDidMount()
{
AsyncStorage.getItem('cart').then((cart)=>{
if (cart !== null) {
// We have data!!
const cartfood = JSON.parse(cart)
this.setState({dataCart:cartfood})
}
})
.catch((err)=>{
alert(err)
})
}
render
render() {
return (
<View style={{flex:1,alignItems: 'center', justifyContent: 'center'}}>
<View style={{height:20}} />
<Text style={{fontSize:32,fontWeight:"bold",color:"#33c37d"}}>Cart food</Text>
<View style={{height:10}} />
<View style={{flex:1}}>
<ScrollView>
{
this.state.dataCart.map((item)=>{
return(
<View style={{width:width-20,margin:10,backgroundColor:'transparent', flexDirection:'row', borderBottomWidth:2, borderColor:"#cccccc", paddingBottom:10}}>
<Image resizeMode={"contain"} style={{width:width/3,height:width/3}} source={{uri: item.food.image}} />
<View style={{flex:1, backgroundColor:'trangraysparent', padding:10, justifyContent:"space-between"}}>
<View>
<Text style={{fontWeight:"bold", fontSize:20}}>{item.food.name}</Text>
<Text>Lorem Ipsum de food</Text>
</View>
<View style={{flexDirection:'row',justifyContent:'space-between'}}>
<Text style={{fontWeight:'bold',color:"#33c37d",fontSize:20}}>${item.price*item.quantity}</Text>
<View style={{flexDirection:'row', alignItems:'center'}}>
<TouchableOpacity>
<Icon name="ios-remove-circle" size={35} color={"#33c37d"} />
</TouchableOpacity>
<Text style={{paddingHorizontal:8, fontWeight:'bold', fontSize:18}}>5</Text>
<TouchableOpacity>
<Icon name="ios-add-circle" size={35} color={"#33c37d"} />
</TouchableOpacity>
</View>
</View>
</View>
</View>
)
})
}
<View style={{height:20}} />
<TouchableOpacity style={{
backgroundColor:"#33c37d",
width:width-40,
alignItems:'center',
padding:10,
borderRadius:5,
margin:20
}}>
<Text style={{
fontSize:24,
fontWeight:"bold",
color:'white'
}}>
CHECKOUT
</Text>
</TouchableOpacity>
<View style={{height:20}} />
</ScrollView>
</View>
</View>
);
}
_
Cart Part 3 : Button Quantity
render
render() {
return (
<View style={{flex:1,alignItems: 'center', justifyContent: 'center'}}>
<View style={{height:20}} />
<Text style={{fontSize:32,fontWeight:"bold",color:"#33c37d"}}>Cart food</Text>
<View style={{height:10}} />
<View style={{flex:1}}>
<ScrollView>
{
this.state.dataCart.map((item,i)=>{
return(
<View style={{width:width-20,margin:10,backgroundColor:'transparent', flexDirection:'row', borderBottomWidth:2, borderColor:"#cccccc", paddingBottom:10}}>
<Image resizeMode={"contain"} style={{width:width/3,height:width/3}} source={{uri: item.food.image}} />
<View style={{flex:1, backgroundColor:'trangraysparent', padding:10, justifyContent:"space-between"}}>
<View>
<Text style={{fontWeight:"bold", fontSize:20}}>{item.food.name}</Text>
<Text>Lorem Ipsum de food</Text>
</View>
<View style={{flexDirection:'row',justifyContent:'space-between'}}>
<Text style={{fontWeight:'bold',color:"#33c37d",fontSize:20}}>${item.price*item.quantity}</Text>
<View style={{flexDirection:'row', alignItems:'center'}}>
<TouchableOpacity onPress={()=>this.onChangeQual(i,false)}>
<Icon name="ios-remove-circle" size={35} color={"#33c37d"} />
</TouchableOpacity>
<Text style={{paddingHorizontal:8, fontWeight:'bold', fontSize:18}}>{item.quantity}</Text>
<TouchableOpacity onPress={()=>this.onChangeQual(i,true)}>
<Icon name="ios-add-circle" size={35} color={"#33c37d"} />
</TouchableOpacity>
</View>
</View>
</View>
</View>
)
})
}
<View style={{height:20}} />
<TouchableOpacity style={{
backgroundColor:"#33c37d",
width:width-40,
alignItems:'center',
padding:10,
borderRadius:5,
margin:20
}}>
<Text style={{
fontSize:24,
fontWeight:"bold",
color:'white'
}}>
CHECKOUT
</Text>
</TouchableOpacity>
<View style={{height:20}} />
</ScrollView>
</View>
</View>
);
}
Function for change Quantity
onChangeQual(i,type)
{
const dataCar = this.state.dataCart
let cantd = dataCar[i].quantity;
if (type) {
cantd = cantd + 1
dataCar[i].quantity = cantd
this.setState({dataCart:dataCar})
}
else if (type==false&&cantd>=2){
cantd = cantd - 1
dataCar[i].quantity = cantd
this.setState({dataCart:dataCar})
}
else if (type==false&&cantd==1){
dataCar.splice(i,1)
this.setState({dataCart:dataCar})
}
}

Hello bro,
When we use to add or remove button the quantity changed correctly, but when we navigate to another screen then back to cart or refresh the app even, the quantity does not change and appears to last change from food.js.
Can you make a function to use AsyncStorage to add or remove from it, please!
Thanks!
You should update the cart in AsyncStorage
I am new on React Native…
How can I update the AsyncStorage and wherein the code?
Thanks for responding!
AsyncStorage.removeItem(‘cart’);
AsyncStorage.setItem(‘cart’, JSON.stringify(dataCar));
Nice tutorial, thanks!
I’m getting this error on my onChangeQual function:
React-native: undefined is not an object (evaluating ‘_this3.state)
Mind to help me?
onChangeQual = (i, type) => {
const dataCar = this.state.dataCart
let cantd = dataCar[i].quantity;
if (type) {
cantd = cantd + 1
dataCar[i].quantity = cantd
this.setState({dataCart: dataCar})
}
else if (type == false && cantd >= 2){
cantd = cantd – 1
dataCar[i].quantity = cantd
this.setState({dataCart: dataCar})
}
else if (type == false && cantd == 1){
dataCar.splice(i, 1)
this.setState({dataCart: dataCar})
}
}
When I add cart, i have error
TypeError: undefined is not an object (evaluating ‘_$$_REQUIRE(_dependencyMap[11], «@react-native-community/async-storage»).AsyncStorage.getItem’)
Can you help me? please