All files / src/components/HiddenInput HiddenInput.tsx

100% Statements 20/20
100% Branches 12/12
100% Functions 6/6
100% Lines 19/19

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 6417x                                   335x   335x 123x     212x 335x                   335x   335x   335x 244x 172x     72x 6x     72x 72x 65x       335x   108x         335x    
import React from 'react';
 
interface HiddenInputProps<T> {
    value: T;
    onReset?: (value: T) => void;
    toStringValue?: (value: T) => string;
    name?: string;
    disabled?: boolean;
    form?: string;
}
export function HiddenInput<T>({
    name,
    value,
    onReset,
    form,
    disabled,
    toStringValue,
}: HiddenInputProps<T>) {
    const ref = useFormResetHandler<T>({initialValue: value, onReset});
 
    if (!name) {
        return null;
    }
 
    const v = toStringValue ? toStringValue(value) : `${value ?? ''}`;
    return <input ref={ref} type="hidden" name={name} value={v} disabled={disabled} form={form} />;
}
 
export function useFormResetHandler<T>({
    initialValue,
    onReset,
}: {
    initialValue: T;
    onReset?: (value: T) => void;
}) {
    const [formElement, setFormElement] = React.useState<HTMLFormElement | null>(null);
 
    const resetValue = React.useRef(initialValue);
 
    React.useEffect(() => {
        if (!formElement || !onReset) {
            return undefined;
        }
 
        const handleReset = () => {
            onReset(resetValue.current);
        };
 
        formElement.addEventListener('reset', handleReset);
        return () => {
            formElement.removeEventListener('reset', handleReset);
        };
    }, [formElement, onReset]);
 
    const ref = React.useCallback(
        (node: HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement | null) => {
            setFormElement(node?.form ?? null);
        },
        [],
    );
 
    return ref;
}