0

app screenshot

I need to access my current cart state which is just a list of products that have been added to the cart, so that I check ids in order to calculate quantity for duplicate products. I realize that one of my issues here is that i've initialized itemsInCart with an empty array but i'm not sure what else to do here since, state can't be destructured without it.

cartReducer.js

const itemsInCart = []
 
export const cartReducer = (state = itemsInCart, action) => {

const { type, payload } = action;
  
  switch (type) {
    case "ADD_TO_CART":
        
      return [
        ...state,
        {
            imgUrl: payload.imgUrl,
            name: payload.name,
            price: payload.price,
            quantity: payload.quantity
        },
      ];
    default:
  }
  return state;
};

Product.js

Clicking the button dispatches the 'ADD_TO_CART' action, adds new products to our cart in state.

import React from 'react';
import {useDispatch} from 'react-redux';

const Product = ({imgUrl, name, price, id }) => {
    const dispatch = useDispatch()
    
    const addToCart = () => {
        
        dispatch({
            type: "ADD_TO_CART",
            payload: {
                imgUrl: imgUrl,
                name: name,
                price: price,
                id: id
            }
        })
        
    }
    return ( 
        <div
          key={id}
          style={{
            textAlign: "center",
            display: "flex",
            border: "1px solid",
            marginBottom: "2rem",
            flexDirection: 'column'
          }}
        >
          <img
            src={imgUrl}
            style={{ height: "5rem", width: "5rem" }}
            alt="The product"
          />
          <h3>{name}</h3>
          <p>${price}.00</p>
          {id}
          <button onClick={()=>addToCart()}>Add To Cart</button>
        </div>
     );
}
 
export default Product;

InCartList.js

Renders list of items in my cart inside CartContainer

import React from "react";
import { useSelector } from "react-redux";
import CartItem from "./CartItem";

const ProductList = () => {
  const allState = useSelector((state) => state.cart);
  const renderProducts = () => {
    return allState.map((product) => {
      return (
        <CartItem id={product.id} quantity={product.quantity}key={product.id} name={product.name} price={product.price}/>
      );
    });
  };
  return <>{renderProducts()}</>;
};

export default ProductList;
qb1234
  • 155
  • 2
  • 14

1 Answers1

0

You shouldn't place any logic inside reducer (reducer should only pure function)

You can try to get state you want before dispatch action ADD_TO_CART

  1. use getStateToProps function
  2. use store which should be exported when initialized inside App component (I guess)
export const store = configureAppStore(history);
cuongdevjs
  • 711
  • 6
  • 15