UNPKG

fra-product-card

Version:

Este es un paquete de pruebas de despliegue eb NPM

57 lines (46 loc) 1.37 kB
import { useEffect, useRef, useState } from 'react' import { InitialValues, onChangeArgs, Product } from '../interfaces/interfaces' export 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) => { let newValue = Math.max(counter + value, 0) if (initialValues?.maxCount) { newValue = Math.min(newValue, initialValues.maxCount) } setCounter(newValue) onChange && onChange({ count: newValue, product }) } const reset = () => { setCounter(initialValues?.count || value) } useEffect(() => { if (!isMounted.current) return setCounter(initialValues?.count || value) }, [value, initialValues]) useEffect(() => { isMounted.current = true }, []) return { counter, value, isMaxCountReached: !!initialValues?.count && initialValues.maxCount === counter, maxCount: initialValues?.maxCount, increaseBy, reset, } }