Search code examples
reactjsreact-reduxredux-toolkit

How to take an array from store?


I have a app that adds a product to the cart. I implement the application through the Redux Toolkit. When I click on the "Add to cart" button, all information about the product should be displayed in the cart.

Now the problem is that the added goods do not get into the array. An empty array is output to the console each time. How can you I this?

import { createSlice } from "@reduxjs/toolkit";

const initialState = {
  productsArr: {
    items: [],
  },
};

const cartSlice = createSlice({
  name: "cart",
  initialState,
  reducers: {
    addItemToCart: (state, action) => {
      state.productArr.items.concat([
        {
          id: action.payload.productId,
          title: action.payload.productTitle,
        },
      ]);
      state.productArr.totalQuantity += 1;
    },
  },
});

// these exports should stay the way they are
export const { addItemToCart} = cartSlice.actions;

export default cartSlice.reducer;

const ProductItem = (props) => {
  const { title, price, description, id } = props;
  const productTitle = title;
  const productId = id;
  const dispatch = useDispatch();
  const addToCartHandler = () => {
    console.log(addItemToCart({ productId, productTitle }));
    dispatch(addItemToCart({ productId, productTitle }));
  };

  return (
    <li className={classes.item}>
      <Card>
        <header>
          <h3>{title}</h3>
          <div className={classes.price}>${price.toFixed(2)}</div>
        </header>
        <p>{description}</p>
        <div className={classes.actions}>
          <button onClick={addToCartHandler}>Add to Cart</button>
        </div>
      </Card>
    </li>
  );
};

const Cart = (props) => {
  const cartItems = useSelector((state) => state.cart.productArr.items);
  console.log(cartItems);

  return(
    <Card className={classes.cart}>
      <h2>Your Shopping Cart</h2>
      <ul>
        {cartItems.map((cartItem) => (
          <CartItem
            item={{
              title: cartItem.title,
              // quantity: item.quantity,
              // total: item.totalPrice,
              // price: item.price,
              key: cartItem.id,
            }}
          />
        ))}
      </ul>
    </Card>
  )
};


Solution

  • I think it should be

        State.productArr.items.push(
    {
          id: action.payload.productId,
          title: action.payload.productTitle,
    });
    

    Did you try with push method??