React and Redux issue

Viewed 53

I have been facing an issue with my code that whenever I add something to a cart it's being added but when am changing the quantity it adds another product with the same id and the new quantity amount even tho i have made a unique id and that's not working as it should be working: Example of what am saying: https://imgur.com/a/T1y1wdM

cartReducer.js


const initialState = {
  cartItems: [],
};
export const cartReducer = (state = initialState, action) => {
  switch (action.type) {
    case CART_ADD_ITEM:
      const item = action.payload;
      state.cartItems.push(item)
      if (state.cartItems.length > 0) {
        const existItem = state.cartItems.find(
          (x) => x.id === item.id
        );

        if (existItem) {
          return {
            ...state,
            cartItems: state.cartItems.map((x) =>
              x.id === existItem.id ? item : x
            ),
            
          };
        }
      } else {
        return {
          ...state,
          cartItems: [...state.cartItems, item],
        };
      }
      break;
    default:
      return state;
      
  }

};

CartScreen.js

import { useDispatch, useSelector } from "react-redux";
import Message from "../components/Message";
import { Link, useNavigate, useParams, useLocation } from "react-router-dom";
import {
  Row,
  Col,
  ListGroup,
  Image,
  Form,
  Button,
  Card,
} from "react-bootstrap";
import { addToCart, editQty } from "../actions/cartActions";

const CartScreen = () => {
  const productId = useParams();
  const location = useLocation();
  const qty = location.search ? Number(location.search.split("=")[1]) : 1;
  const dispatch = useDispatch();

  const cart = useSelector((state) => state.cart);
  const { cartItems } = cart;
  useEffect(() => {
    if (productId) {
      dispatch(addToCart(productId, qty));
    }
  }, [dispatch, productId, qty]);
  const removeFromCartHandler = (id) => {
    console.log("rmeoved")
  }
  return (
    <Row>
      <Col md={8}>
        <h1>Shopping Cart</h1>
        {cartItems.length === 0 ? (
          <Message>
            Your cart is empty <Link to="/">Go back</Link>{" "}
          </Message>
        ) : (
          <ListGroup variant="flush">
            {cartItems.map((item, index) => (
              <ListGroup.Item key={index+1}>
                <Row>
                  <Col md={2}>
                    <Image
                      src={item.image}
                      alt={item.name}
                      fluid
                      rounded
                    ></Image>
                  </Col>
                  <Col md={3}>
                    <Link to={`/product/${item.id}`}>{item.name}</Link>
                  </Col>
                  <Col md={3}>
                    ${item.price}
                  </Col>
                  <Col md={2}>
                    <Form.Control
                      as="select"
                      value={item.qty}
                      onChange={(e) => {
                        dispatch(addToCart(item, Number(e.target.value)));
                      }}
                    >
                      {[...Array(item.countInStock).keys()].map((x) => (
                        <option key={x + 1} value={x + 1}>
                          {x + 1}
                        </option>
                      ))}
                    </Form.Control>
                  </Col>
                  <Col md={2}>
                    <Button type="button" variant="light" onClick={()=>{
                      removeFromCartHandler(item.product)
                    }}><i className="fa fa-trash"></i></Button>
                  </Col>
                </Row>
              </ListGroup.Item>
            ))}
          </ListGroup>
        )}
      </Col>
      <Col md={2}></Col>
      <Col md={2}></Col>
    </Row>
  );
};
export default CartScreen;

cartActions.js

import { CART_ADD_ITEM, CART_FAIL_ITEM, CART_UPDATE_ITEM } from "../constants/cartConstants";
import { useParams, useLocation } from "react-router-dom";

export const addToCart = (id, qty) => async (dispatch, getState) => {
  try {
    const url = `/api/products/${id.id}`;
    const { data } = await axios.get(url);
    dispatch({
      type: CART_ADD_ITEM,
      
      payload: {
        id: data._id,
        name: data.name,
        image: data.image,
        price: data.price,
        countInStock: data.countInStock,
        qty,
      },
    });
  } catch (error) {
    dispatch({
      type: CART_FAIL_ITEM,
      payload:
        error.response && error.response.data.message
          ? error.response.data.message
          : error.message,
    });
  }
  localStorage.setItem("cartItems", JSON.stringify(getState().cart.cartItems));
}; ```
0 Answers
Related