简体   繁体   中英

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!

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM