diff --git a/apps/web/components/profile/profile-field.tsx b/apps/web/components/profile/profile-field.tsx index 932e3ea..89d385e 100644 --- a/apps/web/components/profile/profile-field.tsx +++ b/apps/web/components/profile/profile-field.tsx @@ -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) => { @@ -62,6 +48,31 @@ export function ProfileField({ ); } +function useDebouncedOnChangeCallback( + callback: ((value: CustomerInput) => Promise | 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(null);