function Carts() {
let cartEval = [];
const cartData = useSelector((state) => state.cartProducts);
cartEval = cartData.map((item) => evalCart(item));
function evalCart(a) {
if (cartEval.find((b) => b.id == a.id)) {
return { ...b, numOfTimes: numOfTimes + 1 };
} else {
return {
id: a.id,
numOfTimes: 1,
prodTitle: a.title,
price: a.price,
};
}
}
const totalPrice = cartData
.map((item) => item.price)
.reduce((x, y) => x + y, 0);
function cartRender({ item }) {
return (
<View>
<View>
<View>
<Text>{item.numOfTimes}</Text>
<Text>{item.prodTitle}</Text>
<Text>{item.price}</Text>
<Text>Delete Button</Text>
</View>
</View>
</View>
);
}
return (
<View>
<View>
<Text>Total Sum of Items:{totalPrice}</Text>
</View>
<FlatList data={cartEval} renderItem={cartRender} />
</View>
);
}
const styles = StyleSheet.create({});
export default Carts;
This is what I want to achieve:
I need the function evalCart(a) to check if the item.id exist in the cartEval. If the id exists, increase item.nuofItems by 1. If it does not, create a new item with the id in the cartEval array.
But every time the function is called it returns false, hence the first part of the if statement never executes. only the else part. What am I doing wrong?
I was finally able to solve the puzzle. This is my solution below
function Carts() {
let cartEval = [];
const cartData = useSelector((state) => state.cartProducts);
cartData.map((item) => evalCart(item));
function evalCart(a) {
if (cartEval.find((b) => b.id == a.id)) {
const dummy = cartEval.filter((d) => d.id == a.id)[0];
cartEval.splice(cartEval.indexOf(dummy), 1, {
...dummy,
numOfTimes: dummy.numOfTimes + 1,
});
} else {
cartEval.push({
id: a.id,
numOfTimes: 1,
prodTitle: a.title,
price: a.price,
});
}
}
const totalPrice = cartData
.map((item) => item.price)
.reduce((x, y) => x + y, 0);
function cartRender({ item }) {
return (
<View>
<View>
<View>
<Text>{item.numOfTimes}</Text>
<Text>{item.prodTitle}</Text>
<Text>{item.price}</Text>
<Text>Delete Button</Text>
</View>
</View>
</View>
);
}
return (
<View>
<View>
<Text>Total Sum of Items:{totalPrice}</Text>
</View>
<FlatList data={cartEval} renderItem={cartRender} />
</View>
);
}
const styles = StyleSheet.create({});
export default Carts;
Thanks for your contributions