0

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?

2
  • Why not just read item.cartQuantity, if it is a number? <Text>{item.cartQuantity}</Text>. In your current setup, you are mapping cartProducts to quantity, so if there is more than one item in cartProducts, it should be expected that the quantity array would contain more than one item as well Commented Sep 28, 2022 at 13:35
  • I tried that and got variable undefined error that why I opted the mapping route.. I'm relatively new to this. Is there another way out? Commented Sep 28, 2022 at 14:12

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.