move debounce functional to hook

This commit is contained in:
vchikalkin 2025-01-06 18:06:03 +03:00
parent 702fc131de
commit c8282e8c04

View File

@ -24,21 +24,7 @@ export function ProfileField({
value: initialValue,
}: ProfileFieldProps) {
const [value, setValue] = useState(initialValue);
const [isPending, setIsPending] = useState(false);
const debouncedCallback = useDebouncedCallback((newValue: string) => {
if (!onChange || !fieldName) return;
setIsPending(true);
const result = onChange({ [fieldName]: newValue });
if (result instanceof Promise) {
result.finally(() => setIsPending(false));
} else {
setIsPending(false);
}
}, 300);
const { debouncedCallback, isPending } = useDebouncedOnChangeCallback(onChange, fieldName);
const inputRef = useFocus(isPending);
const handleChange = (event: ChangeEvent<HTMLInputElement>) => {
@ -62,6 +48,31 @@ export function ProfileField({
);
}
function useDebouncedOnChangeCallback(
callback: ((value: CustomerInput) => Promise<void> | void) | undefined,
fieldName: string | undefined,
) {
const [isPending, setIsPending] = useState(false);
const debouncedCallback = useDebouncedCallback((newValue: string) => {
if (!callback || !fieldName) return;
setIsPending(true);
const result = callback({ [fieldName]: newValue });
if (result instanceof Promise) {
result.finally(() => setIsPending(false));
} else {
setIsPending(false);
}
}, 300);
return {
debouncedCallback,
isPending,
};
}
function useFocus(isPending: boolean) {
const inputRef = useRef<HTMLInputElement | null>(null);