|
| 1 | +import { TextInput } from '@carbon/react'; |
| 2 | +import React, { ChangeEvent, useEffect, useMemo, useState } from 'react'; |
| 3 | +import { useStockItemBatchNos } from './batch-no-selector.resource'; |
| 4 | +import { TextInputSkeleton } from '@carbon/react'; |
| 5 | + |
| 6 | +type UniqueBatchNoEntryInputProps = { |
| 7 | + defaultValue?: string; |
| 8 | + onValueChange?: (value: string) => void; |
| 9 | + error?: string; |
| 10 | + stockItemUuid: string; |
| 11 | +}; |
| 12 | +const UniqueBatchNoEntryInput: React.FC<UniqueBatchNoEntryInputProps> = ({ |
| 13 | + defaultValue, |
| 14 | + onValueChange, |
| 15 | + error, |
| 16 | + stockItemUuid, |
| 17 | +}) => { |
| 18 | + const { isLoading, stockItemBatchNos } = useStockItemBatchNos(stockItemUuid); |
| 19 | + const [value, setValue] = useState(defaultValue); |
| 20 | + const [_error, setError] = useState<string>(); |
| 21 | + |
| 22 | + const batchNoAlreadyUsed = useMemo( |
| 23 | + () => stockItemBatchNos?.findIndex((batchNo) => batchNo.batchNo === value) !== -1, |
| 24 | + [stockItemBatchNos, value], |
| 25 | + ); |
| 26 | + |
| 27 | + useEffect(() => { |
| 28 | + if (defaultValue) setValue(defaultValue); |
| 29 | + }, [defaultValue]); |
| 30 | + |
| 31 | + useEffect(() => { |
| 32 | + if (batchNoAlreadyUsed) { |
| 33 | + setError('Batch number already used'); |
| 34 | + } else { |
| 35 | + setError(undefined); |
| 36 | + onValueChange?.(value); |
| 37 | + } |
| 38 | + }, [value, onValueChange, batchNoAlreadyUsed, setError]); |
| 39 | + |
| 40 | + if (isLoading) return <TextInputSkeleton />; |
| 41 | + |
| 42 | + return ( |
| 43 | + <TextInput |
| 44 | + size="sm" |
| 45 | + maxLength={50} |
| 46 | + onChange={(e: ChangeEvent<HTMLInputElement>) => setValue(e.target.value)} |
| 47 | + value={value} |
| 48 | + invalidText={_error ?? error} |
| 49 | + invalid={_error ?? error} |
| 50 | + /> |
| 51 | + ); |
| 52 | +}; |
| 53 | + |
| 54 | +export default UniqueBatchNoEntryInput; |
0 commit comments