I have a basic cart that I am implementing with react reduxjs toolkit. I am able to add items to cart successfully. The challenge I'm facing is when rendering the quantity to the UI. The quantity items are rendered side by side of all the products instead of being rendered as individual quantity items beside each item. I am trying to map the quantity to its product.
See screenshot on this link..... imageitems quantity rendered side to side
The first item should have a quantity of 3 and the second item a quantity of 2, instead both 3 and 2 are in the same field side to side for both items
Below is my reducer (cartSlice.js file)
import { createSlice } from "@reduxjs/toolkit";
const cartSlice = createSlice({
name: "cart",
initialState: [],
reducers: {
addToCart(state, action) {
const newItem = action.payload;
const item = state.find((obj) => {
return obj.product === newItem.product;
});
if (item) {
item.cartQuantity++;
} else {
const tempProduct = { ...action.payload, cartQuantity: 1 };
state.push(tempProduct);
}
},
clearCart(state) {
return (state = []);
},
},
});
export const { addToCart, clearCart } = cartSlice.actions;
export default cartSlice.reducer;
I am using mapStateToProps to map the quantity field to the UI.
const cartProducts = props.cartSlice;
const quantity = cartProducts.map((item, i) => item.cartQuantity);
. . .
<Text> {quantity}</Text>
. . .
const mapStateToProps = (state) => {
const { cartSlice } = state;
return {
cartSlice: cartSlice,
};
How can I change my code to display(render) the quantity correctly?