feat: enhance debounced input handling in TypeInput component

This commit is contained in:
faisolavolut 2025-04-23 11:33:17 +07:00
parent 43795dab6c
commit 282b351204
1 changed files with 22 additions and 8 deletions

View File

@ -368,15 +368,30 @@ export const TypeInput: React.FC<any> = ({
type = "text"; type = "text";
} }
} }
const latestValueRef = React.useRef<string | null>(null);
const debouncedOnChange = React.useMemo( const debouncedOnChange = React.useMemo(
() => () =>
debounce((event: React.ChangeEvent<HTMLInputElement>) => { debounce(() => {
if (typeof onChange === "function") { if (typeof onChange === "function" && latestValueRef.current !== null) {
onChange(fm.data[name]); console.log("onChange", latestValueRef.current);
onChange(latestValueRef.current);
} }
}, 1500), }, 1000),
[] []
); );
const handleInputChange = (event: React.ChangeEvent<HTMLInputElement>) => {
latestValueRef.current = event.currentTarget.value; // Simpan nilai terbaru
debouncedOnChange(); // Panggil fungsi debounce
};
useEffect(() => {
return () => {
debouncedOnChange.cancel(); // Bersihkan debounce saat komponen unmount
};
}, [debouncedOnChange]);
return ( return (
<> <>
<Input <Input
@ -402,16 +417,15 @@ export const TypeInput: React.FC<any> = ({
value={value} value={value}
type={!type ? "text" : type_field} type={!type ? "text" : type_field}
onChange={(ev) => { onChange={(ev) => {
setInputValue(ev.currentTarget.value);
fm.data[name] = ev.currentTarget.value; fm.data[name] = ev.currentTarget.value;
fm.render(); fm.render();
if (!isDebounce) { if (!isDebounce) {
if (typeof onChange === "function") { if (typeof onChange === "function") {
onChange(fm.data[name]); onChange(ev.currentTarget.value);
} }
} else { } else {
setInputValue(ev.currentTarget.value); handleInputChange(ev);
debouncedOnChange(inputValue);
return () => debouncedOnChange.cancel();
} }
}} }}
/> />