From 282b351204ec1b2f5c68a15d08b93170c77a85b4 Mon Sep 17 00:00:00 2001 From: faisolavolut Date: Wed, 23 Apr 2025 11:33:17 +0700 Subject: [PATCH] feat: enhance debounced input handling in TypeInput component --- components/form/field/TypeInput.tsx | 30 +++++++++++++++++++++-------- 1 file changed, 22 insertions(+), 8 deletions(-) diff --git a/components/form/field/TypeInput.tsx b/components/form/field/TypeInput.tsx index 6d62077..3b6df01 100644 --- a/components/form/field/TypeInput.tsx +++ b/components/form/field/TypeInput.tsx @@ -368,15 +368,30 @@ export const TypeInput: React.FC = ({ type = "text"; } } + + const latestValueRef = React.useRef(null); + const debouncedOnChange = React.useMemo( () => - debounce((event: React.ChangeEvent) => { - if (typeof onChange === "function") { - onChange(fm.data[name]); + debounce(() => { + if (typeof onChange === "function" && latestValueRef.current !== null) { + console.log("onChange", latestValueRef.current); + onChange(latestValueRef.current); } - }, 1500), + }, 1000), [] ); + + const handleInputChange = (event: React.ChangeEvent) => { + latestValueRef.current = event.currentTarget.value; // Simpan nilai terbaru + debouncedOnChange(); // Panggil fungsi debounce + }; + + useEffect(() => { + return () => { + debouncedOnChange.cancel(); // Bersihkan debounce saat komponen unmount + }; + }, [debouncedOnChange]); return ( <> = ({ value={value} type={!type ? "text" : type_field} onChange={(ev) => { + setInputValue(ev.currentTarget.value); fm.data[name] = ev.currentTarget.value; fm.render(); if (!isDebounce) { if (typeof onChange === "function") { - onChange(fm.data[name]); + onChange(ev.currentTarget.value); } } else { - setInputValue(ev.currentTarget.value); - debouncedOnChange(inputValue); - return () => debouncedOnChange.cancel(); + handleInputChange(ev); } }} />