UNPKG

pmcm-product-card

Version:

Este es un paquete de pruebas de despliegue NPM

51 lines (43 loc) 1.22 kB
import { useState, useEffect, useRef } from "react"; import { InitialValues, onChangeArgs, Product } from "../interfaces/interfaces"; interface useProductArgs { product: Product; onChange?: (args: onChangeArgs) => void; value?: number; initialValues?: InitialValues; } 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) => { const newValue = Math.max( Math.min(initialValues?.maxCount || Infinity, counter + value), 0 ); setCounter(newValue); onChange && onChange({ count: newValue, product }); }; const reset = () => { setCounter(initialValues?.count || value); }; useEffect(() => { if (!isMounted.current) return; setCounter(value); }, [value]); useEffect(() => { isMounted.current = true; }, []); return { counter, maxCount: initialValues?.maxCount, isMaxCountReached: !!initialValues?.count && initialValues?.maxCount === counter, increaseBy, reset, }; };