As a newcomer to React Native, I encountered an error when calling getItemsCount.
*To view images, please click on the following links:
https://i.sstatic.net/wbwjZ.png
This snippet shows the code for CartIcon.js:
import React, {useContext} from 'react';
import {View, Text, StyleSheet} from 'react-native';
import {CartContext} from './CartContext';
export function CartIcon({navigation}){
const {getItemsCount} = useContext(CartContext);
return(
<View style = {styles.container}>
<Text style = {styles.text}
onPress = {() => {
navigation.navigate('Cart');
}}
>Cart ({getItemsCount()}) </Text>
</View>
);
}
const styles = StyleSheet.create({
container: {
marginHorizontal: 10,
backgroundColor: '#515b8c',
height: 40,
padding: 15,
borderRadius: 38/2,
alignItems: 'center',
justifyContent: 'center',
},
text: {
color: '#ccc',
fontWeight: 'normal',
},
});
https://i.sstatic.net/ABYHm.png
The code provided below is for CartContext.js:
import React, {createContext, useState} from 'react';
import {getProduct} from './productService.js';
export const CartContext = createContext();
export function CartProvider(props){
const [items, setItems] = useState([]);
function addItemToCart(id){
const product = getProduct(id);
setItems((prevItems) => {
const item = prevItems.find((item) => (item.id == id));
if(!item){
return [...prevItems, {
id,
qty: 1,
product,
totalPrice: product.price
}];
}
else{
return prevItems.map((item) => {
if(item.id == id){
item.qty++;
item.totalPrice += product.price;
}
return item;
});
}
});
}
function getItemsCount(){
return items.reduce((sum,item) => (sum+item.qty),0);
}
function getTotalPrice(){
return items.reduce((sum,item) => (sum+item.totalPrice),0);
}
return(
<CartContext.Provider
value = {{items,setItems,getItemsCount,addItemToCart,getTotalPrice}}>
{props.children}
</CartContext.Provider>
);
}