UNPKG

fbc-product-card

Version:

Este es un paquete de pruebas de despliegue en NPM

59 lines (49 loc) 1.38 kB
import { useEffect, useRef, useState } from "react"; import { onChangeArgs, Product, InitialValues } 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 !== undefined ? initialValues.count : value ); const isMounted = useRef(false); const increaseBy = (value: number) => { 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 || value); }; useEffect(() => { if (!isMounted.current) return; if (initialValues?.count === undefined) { setCounter(value); } }, [value]); useEffect(() => { isMounted.current = true; }, []); return { counter, increaseBy, isMaxCountReached: !!initialValues?.count && initialValues.maxCount === counter, maxCount: initialValues?.maxCount, reset, }; };