UNPKG

ecr-product-card

Version:

Este es un paquete de pruebas de despliegue en NPM

52 lines (42 loc) 1.43 kB
import { useEffect, useRef, useState } from "react" import { InitialValues, Product, ProductChangeProps } from "../interfaces"; interface useProductArgs { product: Product; value?: number; initialValues?: InitialValues; onChange?: (args: ProductChangeProps) => void; } export const useProduct = ({ onChange, product, value = 0, initialValues }: useProductArgs) => { const [counter, setCounter] = useState<number>(initialValues?.count || value); const isMounted = useRef(false); const increaseBy = (value: number,) => { // if (initialValues.maxCount && counter + value > initialValues.maxCount) return; let newValue = Math.max(counter + value, 0) if (initialValues?.maxCount) { newValue = Math.min(newValue, initialValues.maxCount) } setCounter(newValue); if (onChange) { onChange({ count: newValue, product }); } } const reset = () => setCounter(initialValues?.count || 0); useEffect(() => { if (!isMounted.current) return; setCounter(value) }, [value]) useEffect(() => { isMounted.current = true; }, []) return { counter, maxCount: initialValues?.maxCount, isMaxCountReached: !!initialValues?.count && counter === initialValues.maxCount, increaseBy, reset, } }