Skip to content
TheChatArchiveThe Chat Archive
o1-mini-2024-09-12· OpenAIAi2 WildChat-4.8M (AI2)

qty shouldn't be larger than selectedSize.qty (if there is any size) or…

  1. User

    qty shouldn't be larger than selectedSize.qty (if there is any size) or selectedColor.qty (if there is any color) also if the qty is 0, show out of stock for selected size or selected color. 'use client';

    import React, { useState, useEffect, useCallback, useMemo } from 'react'; import { motion, AnimatePresence } from 'framer-motion'; import { Minus, Plus, ShoppingCart } from 'lucide-react'; import { useNotification } from '@/components/NotificationContext'; import '@/components/NotificationStyles.css'; import Link from 'next/link';

    const formatPrice = (price) => { if (price == null || price === Infinity) return 'N/A'; const formattedPrice = price >= 10000 ? price.toLocaleString() : price.toString(); return ${formattedPrice} IQD; };

    const ProductModal = ({ isOpen, onClose, productData }) => { const [selectedSize, setSelectedSize] = useState(null); const [quantity, setQuantity] = useState(1); const [isInCart, setIsInCart] = useState(false); const { addNotification } = useNotification();

    const product = productData.product;
    
    // Compute total price dynamically
    const totalPrice = useMemo(() => {
        return selectedSize ? parseFloat(selectedSize.price) * quantity : 0;
    }, [selectedSize, quantity]);
    
    // Check if the product is in the cart
    const checkIfInCart = useCallback(() => {
        try {
            const cart = JSON.parse(localStorage.getItem('cart')) || [];
            const isItemInCart = cart.some(
                (item) =>
                    item.product_id === product.id &&
                    item.size_id === selectedSize?.id
            );
            setIsInCart(isItemInCart);
        } catch (error) {
            console.error('Error accessing localStorage:', error);
            setIsInCart(false);
        }
    }, [product.id, selectedSize]);
    
    // Set default selected size on product change
    useEffect(() => {
        if (product?.sizes?.length > 0) {
            setSelectedSize(product.sizes[0]);
        }
    }, [product]);
    
    // Check if the product is in the cart whenever selectedSize changes
    useEffect(() => {
        checkIfInCart();
    }, [selectedSize, checkIfInCart]);
    
    // Handle adding product to cart
    const handleAddToCart = useCallback(() => {
        if (!selectedSize) return;
    
        const cartItem = {
            product_id: product.id,
            size_id: selectedSize.id,
            qty: quantity,
            price: selectedSize.price,
        };
    
        try {
            const cart = JSON.parse(localStorage.getItem('cart')) || [];
            const existingItemIndex = cart.findIndex(
                (item) =>
                    item.product_id === cartItem.product_id &&
                    item.size_id === cartItem.size_id
            );
    
            if (existingItemIndex > -1) {
                cart[existingItemIndex].qty += quantity;
            } else {
                cart.push(cartItem);
            }
    
            localStorage.setItem('cart', JSON.stringify(cart));
            setIsInCart(true);
            addNotification('success', 'Added to cart successfully');
        } catch (error) {
            console.error('Error updating cart:', error);
            addNotification('error', 'Failed to add to cart');
        }
    }, [product.id, selectedSize, quantity, addNotification]);
    
    if (!isOpen || !product) return null;
    
    return (
        <AnimatePresence>
            <motion.div
                initial={{ opacity: 0 }}
                animate={{ opacity: 1 }}
                exit={{ opacity: 0 }}
                className="fixed inset-0 bg-black bg-opacity-30 flex items-end justify-center z-50"
                onClick={onClose}
                aria-modal="true"
                role="dialog"
            >
                <motion.div
                    initial={{ y: '100%' }}
                    animate={{ y: 0 }}
                    exit={{ y: '100%' }}
                    transition={{ type: 'spring', damping: 25, stiffness: 500 }}
                    className="bg-white rounded-t-3xl w-full p-6 relative"
                    onClick={(e) => e.stopPropagation()}
                >
                    <div className="w-9 h-1 bg-[#00003C] opacity-70 rounded-full mx-auto mb-6" />
    
                    <h2 className="text-xl mb-4 font-sans">{product.name}</h2>
    
                    {product.has_size && (
                        <div className="mb-4">
                            <label htmlFor="size-select" className="sr-only">
                                Select Size
                            </label>
                            <select
                                id="size-select"
                                value={selectedSize ? selectedSize.id : ''}
                                onChange={(e) =>
                                    setSelectedSize(
                                        product.sizes.find(
                                            (size) => size.id.toString() === e.target.value
                                        )
                                    )
                                }
                                className="w-44 p-2 border border-[rgba(105,92,92,0.5)] rounded-lg font-serif text-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
                            >
                                <option value="" disabled>
                                    Select a Size
                                </option>
                                {product.sizes.map((size) => (
                                    <option key={size.id} value={size.id}>
                                        {size.name}
                                    </option>
                                ))}
                            </select>
                            {!selectedSize && (
                                <p className="text-[#C91C1C] text-xs mt-2 font-sans">
                                    Please choose Size
                                </p>
                            )}
                        </div>
                    )}
    
                    {product.has_color && product.colors && product.colors.length > 0 && (
                        <div className="mb-6">
                            <h3 className="text-xl font-medium mb-2 font-sans">Color</h3>
                            <div className="flex space-x-5 mb-2">
                                {product.colors.map((color) => (
                                    <button
                                        key={color.id}
                                        className={`w-20 h-20 rounded-full border-2 ${
                                            selectedSize && selectedSize.color_id === color.id
                                                ? 'border-[rgba(105,92,92,0.5)]'
                                                : 'border-transparent'
                                        } flex items-center justify-center focus:outline-none focus:ring-2 focus:ring-blue-500`}
                                        aria-label={`Select color ${color.name}`}
                                        onClick={() => {
                                            // Assuming color selection affects selectedSize
                                            // If not, consider adding a separate state for selectedColor
                                        }}
                                    >
                                        <div
                                            className="w-15 h-15 rounded-full"
                                            style={{ backgroundColor: color.hex }}
                                        />
                                    </button>
                                ))}
                            </div>
                            <div className="flex justify-between px-2">
                                {product.colors.map((color) => (
                                    <span key={color.id} className="text-sm font-serif">
                                        {color.name}
                                    </span>
                                ))}
                            </div>
                        </div>
                    )}
    
                    <div className="flex font-serif justify-between items-center mb-6">
                        <p className="text-lg font-medium">{formatPrice(totalPrice)}</p>
                        <div className="flex items-center space-x-4">
                            <button
                                className="w-8 h-8 rounded-full border border-gray-300 flex items-center justify-center focus:outline-none focus:ring-2 focus:ring-blue-500 disabled:opacity-50"
                                onClick={() => setQuantity((prev) => Math.max(1, prev - 1))}
                                disabled={quantity <= 1}
                                aria-label="Decrease quantity"
                            >
                                <Minus className="w-4 h-4 text-[#3B5345]" />
                            </button>
                            <span className="text-lg">{quantity}</span>
                            <button
                                className="w-8 h-8 rounded-full border border-gray-300 flex items-center justify-center focus:outline-none focus:ring-2 focus:ring-blue-500"
                                onClick={() => setQuantity((prev) => prev + 1)}
                                aria-label="Increase quantity"
                            >
                                <Plus className="w-4 h-4 text-[#3B5345]" />
                            </button>
                        </div>
                    </div>
    
                    <div className="flex font-serif space-x-4">
                        {isInCart ? (
                            <Link
                                href="/cart"
                                prefetch={false}
                                className="flex-1 font-serif bg-[rgba(59,83,69,0.05)] text-[#3B5345] py-3 rounded-lg font-medium text-base md:text-lg flex items-center justify-center transition duration-300 border border-[#3B5345] hover:bg-[rgba(59,83,69,0.1)]"
                            >
                                <ShoppingCart className="mr-2" />
                                Buy Now
                            </Link>
                        ) : (
                            <button
                                className={`flex-1 ${
                                    selectedSize
                                        ? 'bg-[#3B5345] text-white hover:bg-[#2d4233]'
                                        : 'bg-gray-300 text-gray-500 cursor-not-allowed'
                                } py-3 rounded-lg font-medium text-base md:text-lg flex items-center justify-center transition duration-300`}
                                onClick={handleAddToCart}
                                disabled={!selectedSize}
                                aria-label="Add to cart"
                            >
                                <ShoppingCart className="mr-2" />
                                Add To Cart
                            </button>
                        )}
                        <button
                            className="flex-1 bg-gray-200 text-gray-800 py-3 rounded-lg font-medium text-base md:text-lg hover:bg-gray-300 transition duration-300"
                            onClick={onClose}
                            aria-label="Close modal"
                        >
                            Close
                        </button>
                    </div>
                </motion.div>
            </motion.div>
        </AnimatePresence>
    );
    

    };

    export default React.memo(ProductModal);

  2. Assistant

    To implement the desired functionality—restricting the quantity (qty) based on the selected size or color and displaying an "Out of Stock" message when applicable—you need to incorporate additional state management and conditional rendering in your ProductModal component.

    Below, I'll guide you through the necessary modifications and enhancements to achieve this behavior:

    1. State Management for Selected Color:

      • Introduce a selectedColor state to track the user's color choice.
      • Ensure that both size and color selections impact the available quantity.
    2. Determining Maximum Available Quantity (maxQty):

      • Compute maxQty based on the selected size and/or color.
      • If both size and color are selected, and if their combination defines a unique variant, ensure that maxQty reflects this specific variant's stock.
      • If only size or color is selected, use their respective qty.
    3. Restricting Quantity Selection:

      • Ensure that the user cannot select a quantity greater than maxQty.
      • Disable the "Increase" button if quantity reaches maxQty.
      • Prevent adding to the cart if maxQty is 0.
    4. Displaying "Out of Stock":

      • When maxQty is 0, show an "Out of Stock" message based on the selected size or color.
    5. Handling Variants (If Applicable):

      • If your product data structure includes variants that are combinations of size and color, adjust the logic accordingly to fetch the correct qty for the selected combination.

    Below is the revised ProductModal component with these enhancements:

    'use client';
    
    import React, { useState, useEffect, useCallback, useMemo } from 'react';
    import { motion, AnimatePresence } from 'framer-motion';
    import { Minus, Plus, ShoppingCart } from 'lucide-react';
    import { useNotification } from '@/components/NotificationContext';
    import '@/components/NotificationStyles.css';
    import Link from 'next/link';
    
    const formatPrice = (price) => {
        if (price == null || price === Infinity) return 'N/A';
        const formattedPrice = price >= 10000 ? price.toLocaleString() : price.toString();
        return `${formattedPrice} IQD`;
    };
    
    const ProductModal = ({ isOpen, onClose, productData }) => {
        const [selectedSize, setSelectedSize] = useState(null);
        const [selectedColor, setSelectedColor] = useState(null);
        const [quantity, setQuantity] = useState(1);
        const [isInCart, setIsInCart] = useState(false);
        const { addNotification } = useNotification();
    
        const product = productData.product;
    
        // Compute maxQty based on selected size and/or color
        const maxQty = useMemo(() => {
            let sizeQty = selectedSize ? selectedSize.qty : Infinity;
            let colorQty = selectedColor ? selectedColor.qty : Infinity;
    
            // Assuming that if both size and color are selected, the available qty is the minimum of both
            return Math.min(sizeQty, colorQty);
        }, [selectedSize, selectedColor]);
    
        // Adjust quantity if it exceeds maxQty
        useEffect(() => {
            if (quantity > maxQty) {
                setQuantity(maxQty);
            }
            if (maxQty === 0) {
                setQuantity(0);
            } else if (quantity < 1 && maxQty > 0) {
                setQuantity(1);
            }
        }, [maxQty, quantity]);
    
        // Compute total price dynamically
        const totalPrice = useMemo(() => {
            // Assuming that price is based on size; adjust if based on color or variant
            return selectedSize ? parseFloat(selectedSize.price) * quantity : 0;
        }, [selectedSize, quantity]);
    
        // Check if the product is in the cart
        const checkIfInCart = useCallback(() => {
            try {
                const cart = JSON.parse(localStorage.getItem('cart')) || [];
                const isItemInCart = cart.some(
                    (item) =>
                        item.product_id === product.id &&
                        item.size_id === selectedSize?.id &&
                        item.color_id === selectedColor?.id
                );
                setIsInCart(isItemInCart);
            } catch (error) {
                console.error('Error accessing localStorage:', error);
                setIsInCart(false);
            }
        }, [product.id, selectedSize, selectedColor]);
    
        // Set default selected size and color on product change
        useEffect(() => {
            if (product?.sizes?.length > 0) {
                setSelectedSize(product.sizes[0]);
            } else {
                setSelectedSize(null);
            }
    
            if (product?.colors?.length > 0) {
                setSelectedColor(product.colors[0]);
            } else {
                setSelectedColor(null);
            }
        }, [product]);
    
        // Check if the product is in the cart whenever selectedSize or selectedColor changes
        useEffect(() => {
            checkIfInCart();
        }, [selectedSize, selectedColor, checkIfInCart]);
    
        // Handle adding product to cart
        const handleAddToCart = useCallback(() => {
            if ((!selectedSize && product.has_size) || (!selectedColor && product.has_color)) {
                addNotification('error', 'Please select the required options');
                return;
            }
    
            if (maxQty === 0) {
                addNotification('error', 'Selected option is out of stock');
                return;
            }
    
            const cartItem = {
                product_id: product.id,
                size_id: selectedSize ? selectedSize.id : null,
                color_id: selectedColor ? selectedColor.id : null,
                qty: quantity,
                price: selectedSize ? selectedSize.price : product.price,
            };
    
            try {
                const cart = JSON.parse(localStorage.getItem('cart')) || [];
                const existingItemIndex = cart.findIndex(
                    (item) =>
                        item.product_id === cartItem.product_id &&
                        item.size_id === cartItem.size_id &&
                        item.color_id === cartItem.color_id
                );
    
                if (existingItemIndex > -1) {
                    const newQty = cart[existingItemIndex].qty + quantity;
                    if (newQty > maxQty) {
                        addNotification('error', `Cannot add more than ${maxQty} items`);
                        return;
                    }
                    cart[existingItemIndex].qty = newQty;
                } else {
                    if (quantity > maxQty) {
                        addNotification('error', `Cannot add more than ${maxQty} items`);
                        return;
                    }
                    cart.push(cartItem);
                }
    
                localStorage.setItem('cart', JSON.stringify(cart));
                setIsInCart(true);
                addNotification('success', 'Added to cart successfully');
            } catch (error) {
                console.error('Error updating cart:', error);
                addNotification('error', 'Failed to add to cart');
            }
        }, [product, selectedSize, selectedColor, quantity, addNotification, maxQty]);
    
        if (!isOpen || !product) return null;
    
        return (
            <AnimatePresence>
                <motion.div
                    initial={{ opacity: 0 }}
                    animate={{ opacity: 1 }}
                    exit={{ opacity: 0 }}
                    className="fixed inset-0 bg-black bg-opacity-30 flex items-end justify-center z-50"
                    onClick={onClose}
                    aria-modal="true"
                    role="dialog"
                >
                    <motion.div
                        initial={{ y: '100%' }}
                        animate={{ y: 0 }}
                        exit={{ y: '100%' }}
                        transition={{ type: 'spring', damping: 25, stiffness: 500 }}
                        className="bg-white rounded-t-3xl w-full p-6 relative"
                        onClick={(e) => e.stopPropagation()}
                    >
                        <div className="w-9 h-1 bg-[#00003C] opacity-70 rounded-full mx-auto mb-6" />
    
                        <h2 className="text-xl mb-4 font-sans">{product.name}</h2>
    
                        {product.has_size && (
                            <div className="mb-4">
                                <label htmlFor="size-select" className="sr-only">
                                    Select Size
                                </label>
                                <select
                                    id="size-select"
                                    value={selectedSize ? selectedSize.id : ''}
                                    onChange={(e) =>
                                        setSelectedSize(
                                            product.sizes.find(
                                                (size) => size.id.toString() === e.target.value
                                            )
                                        )
                                    }
                                    className="w-44 p-2 border border-[rgba(105,92,92,0.5)] rounded-lg font-serif text-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
                                >
                                    <option value="" disabled>
                                        Select a Size
                                    </option>
                                    {product.sizes.map((size) => (
                                        <option key={size.id} value={size.id}>
                                            {size.name}
                                        </option>
                                    ))}
                                </select>
                                {!selectedSize && (
                                    <p className="text-[#C91C1C] text-xs mt-2 font-sans">
                                        Please choose Size
                                    </p>
                                )}
                            </div>
                        )}
    
                        {product.has_color && product.colors && product.colors.length > 0 && (
                            <div className="mb-6">
                                <h3 className="text-xl font-medium mb-2 font-sans">Color</h3>
                                <div className="flex space-x-5 mb-2">
                                    {product.colors.map((color) => (
                                        <button
                                            key={color.id}
                                            className={`w-20 h-20 rounded-full border-2 ${
                                                selectedColor && selectedColor.id === color.id
                                                    ? 'border-[rgba(105,92,92,0.5)]'
                                                    : 'border-transparent'
                                            } flex items-center justify-center focus:outline-none focus:ring-2 focus:ring-blue-500`}
                                            aria-label={`Select color ${color.name}`}
                                            onClick={() => setSelectedColor(color)}
                                        >
                                            <div
                                                className="w-15 h-15 rounded-full"
                                                style={{ backgroundColor: color.hex }}
                                            />
                                        </button>
                                    ))}
                                </div>
                                <div className="flex justify-between px-2">
                                    {product.colors.map((color) => (
                                        <span key={color.id} className="text-sm font-serif">
                                            {color.name}
                                        </span>
                                    ))}
                                </div>
                                {!selectedColor && (
                                    <p className="text-[#C91C1C] text-xs mt-2 font-sans">
                                        Please choose Color
                                    </p>
                                )}
                            </div>
                        )}
    
                        {/* Display Out of Stock message */}
                        {maxQty === 0 && (
                            <div className="mb-4">
                                <p className="text-red-600 font-semibold text-center">
                                    Out of Stock
                                </p>
                            </div>
                        )}
    
                        <div className="flex font-serif justify-between items-center mb-6">
                            <p className="text-lg font-medium">{formatPrice(totalPrice)}</p>
                            <div className="flex items-center space-x-4">
                                <button
                                    className="w-8 h-8 rounded-full border border-gray-300 flex items-center justify-center focus:outline-none focus:ring-2 focus:ring-blue-500 disabled:opacity-50"
                                    onClick={() => setQuantity((prev) => Math.max(0, prev - 1))}
                                    disabled={quantity <= 0}
                                    aria-label="Decrease quantity"
                                >
                                    <Minus className="w-4 h-4 text-[#3B5345]" />
                                </button>
                                <span className="text-lg">{quantity}</span>
                                <button
                                    className="w-8 h-8 rounded-full border border-gray-300 flex items-center justify-center focus:outline-none focus:ring-2 focus:ring-blue-500"
                                    onClick={() => setQuantity((prev) => Math.min(prev + 1, maxQty))}
                                    disabled={quantity >= maxQty}
                                    aria-label="Increase quantity"
                                >
                                    <Plus className="w-4 h-4 text-[#3B5345]" />
                                </button>
                            </div>
                        </div>
    
                        <div className="flex font-serif space-x-4">
                            {isInCart ? (
                                <Link
                                    href="/cart"
                                    prefetch={false}
                                    className="flex-1 font-serif bg-[rgba(59,83,69,0.05)] text-[#3B5345] py-3 rounded-lg font-medium text-base md:text-lg flex items-center justify-center transition duration-300 border border-[#3B5345] hover:bg-[rgba(59,83,69,0.1)]"
                                >
                                    <ShoppingCart className="mr-2" />
                                    Buy Now
                                </Link>
                            ) : (
                                <button
                                    className={`flex-1 ${
                                        selectedSize || selectedColor
                                            ? 'bg-[#3B5345] text-white hover:bg-[#2d4233]'
                                            : 'bg-gray-300 text-gray-500 cursor-not-allowed'
                                    } py-3 rounded-lg font-medium text-base md:text-lg flex items-center justify-center transition duration-300`}
                                    onClick={handleAddToCart}
                                    disabled={!selectedSize && product.has_size || !selectedColor && product.has_color || maxQty === 0}
                                    aria-label="Add to cart"
                                >
                                    <ShoppingCart className="mr-2" />
                                    Add To Cart
                                </button>
                            )}
                            <button
                                className="flex-1 bg-gray-200 text-gray-800 py-3 rounded-lg font-medium text-base md:text-lg hover:bg-gray-300 transition duration-300"
                                onClick={onClose}
                                aria-label="Close modal"
                            >
                                Close
                            </button>
                        </div>
                    </motion.div>
                </motion.div>
            </AnimatePresence>
        );
    };
    
    export default React.memo(ProductModal);
    

    Detailed Explanation of Changes

    1. State for selectedColor:

      const [selectedColor, setSelectedColor] = useState(null);
      
      • Added selectedColor to manage the user's color selection.
    2. Updating Color Selection Logic:

      onClick={() => setSelectedColor(color)}
      
      • Updated the color selection buttons to set the selectedColor state when a color is selected.
    3. Computing maxQty:

      const maxQty = useMemo(() => {
          let sizeQty = selectedSize ? selectedSize.qty : Infinity;
          let colorQty = selectedColor ? selectedColor.qty : Infinity;
      
          // If both size and color are selected, take the minimum of both
          return Math.min(sizeQty, colorQty);
      }, [selectedSize, selectedColor]);
      
      • maxQty is determined based on the selected size and color.
      • If both are selected, it takes the minimum of their available quantities to ensure that neither option is oversold.
    4. Adjusting quantity Based on maxQty:

      useEffect(() => {
          if (quantity > maxQty) {
              setQuantity(maxQty);
          }
          if (maxQty === 0) {
              setQuantity(0);
          } else if (quantity < 1 && maxQty > 0) {
              setQuantity(1);
          }
      }, [maxQty, quantity]);
      
      • Ensures that quantity never exceeds maxQty and handles cases where maxQty is 0.
    5. Displaying "Out of Stock":

      {maxQty === 0 && (
          <div className="mb-4">
              <p className="text-red-600 font-semibold text-center">
                  Out of Stock
              </p>
          </div>
      )}
      
      • Conditionally renders an "Out of Stock" message when maxQty is 0.
    6. Restricting Quantity Selection Buttons:

      <button
          ...
          onClick={() => setQuantity((prev) => Math.max(0, prev - 1))}
          disabled={quantity <= 0}
          ...
      >
          <Minus ... />
      </button>
      ...
      <button
          ...
          onClick={() => setQuantity((prev) => Math.min(prev + 1, maxQty))}
          disabled={quantity >= maxQty}
          ...
      >
          <Plus ... />
      </button>
      
      • The "Decrease" button allows the quantity to go down to 0 to facilitate the "Out of Stock" state.
      • The "Increase" button is disabled when quantity reaches maxQty.
    7. Enhancing the "Add to Cart" Button:

      disabled={!selectedSize && product.has_size || !selectedColor && product.has_color || maxQty === 0}
      
      • The "Add to Cart" button is disabled if:
        • A required option (size or color) isn't selected.
        • maxQty is 0, indicating that the selected combination is out of stock.
      • Adjusted the styling to reflect the disabled state appropriately.
    8. Handling Cart Item with Both Size and Color:

      const cartItem = {
          product_id: product.id,
          size_id: selectedSize ? selectedSize.id : null,
          color_id: selectedColor ? selectedColor.id : null,
          qty: quantity,
          price: selectedSize ? selectedSize.price : product.price,
      };
      
      • Included both size_id and color_id in the cartItem to ensure that the correct variant is managed in the cart.
      existingItemIndex = cart.findIndex(
          (item) =>
              item.product_id === cartItem.product_id &&
              item.size_id === cartItem.size_id &&
              item.color_id === cartItem.color_id
      );
      
      • Modified the search to include both size_id and color_id when checking if an item exists in the cart.
    9. Default Selections:

      useEffect(() => {
          if (product?.sizes?.length > 0) {
              setSelectedSize(product.sizes[0]);
          } else {
              setSelectedSize(null);
          }
      
          if (product?.colors?.length > 0) {
              setSelectedColor(product.colors[0]);
          } else {
              setSelectedColor(null);
          }
      }, [product]);
      
      • Automatically selects the first size and color (if available) when the product changes.

    Assumptions & Notes

    1. Product Data Structure:

      • This implementation assumes that each size and color has its own qty attribute.
      • If the product has variants that are combinations of size and color with their own unique qty, you'll need to adjust the logic to fetch the qty based on both selections. This might involve restructuring your data or adding a variant lookup.
    2. Handling Variants:

      • If your system supports variants (specific combinations of size and color), consider adding a variants array in your product data, where each variant has its own size, color, and qty.
      • The maxQty computation would then involve finding the variant that matches both selectedSize and selectedColor and using its qty.
    3. UI/UX Considerations:

      • Ensure that the "Out of Stock" message is prominent to inform users clearly.
      • Consider providing tooltips or additional information if a combination is out of stock to enhance user experience.
    4. Accessibility:

      • Ensure that all interactive elements are keyboard accessible and have appropriate aria attributes for better accessibility.
    5. Optimizing Performance:

      • The use of useMemo and useCallback hooks helps in optimizing performance by memoizing computations and functions, preventing unnecessary re-renders.
    6. Error Handling:

      • The implementation includes basic error handling when interacting with localStorage. Depending on your application's requirements, you might want to enhance this further.

    Final Thoughts

    By integrating these enhancements, your ProductModal component will now effectively manage quantity restrictions based on user selections and provide clear feedback when a product variant is out of stock. Always ensure to test these changes thoroughly to handle various product configurations and edge cases.