elena similea
elena similea

Reputation: 9

Limiting the number of same-product items to 1 in a shopping cart with React JS

I am currently working on my first project, which is a pre-owned clothes and accessories shop. Currently, each time I click the "Add to cart" button, it adds the product, which is great, but given that it should be one item for each product, I want to have it so once you add it to the cart, the product is not available for a second add.

My code looks like this:

ProductCard:

 export default function ProductCard(props) {
      const context = React.useContext(Context);
      const addToCart = () => {
        context.dispatch({
          code: "ADD-PRODUCT-TO-CART",
          payload: props.product,
        });
      };

And the Context:

const reducer = (state, action) => {
  console.log(state, action);
  switch (
    action.code )

This is technically where the magic should happen:

{
    case "ADD-PRODUCT-TO-CART":
      if (state.cart.name === state.cart.name) {
        alert("The maximum quantity for this product is 1");
        console.log("disable button");
      }
      return { ...state, cart: [...state.cart, action.payload] };

    case "REMOVE-FROM-CART":
      console.log(action);
      return {
        ...state,
        cart: state.cart.filter((product, index) => {
          if (action.payload !== index) {
            return true;
          } else {
            return false;
          }
        }),
      };
    default:
      return state;
  }
};

const Context = React.createContext();

const Provider = (props) => {
  const [state, dispatch] = React.useReducer(reducer, initialState);

  return (
    <Context.Provider value={{ state, dispatch }}>
      {props.children}
    </Context.Provider>
  );
};
export { Context, Provider, reducer };

Any suggestion would be helpful!

Thank you!

Upvotes: 0

Views: 150

Answers (1)

Емил Цоков
Емил Цоков

Reputation: 692

Disabling the button Add to card should happen in Product card component based on check if the product id is already present in the cart.

Upvotes: 1

Related Questions