In React component can not debounce handleChange

23 Views Asked by At

I try to implement simple delay-typing functionality in React component

What is working but still without debounce:

const handleChange = useCallback(
        (ev: ChangeEvent<HTMLInputElement>) => {
            if (!isNaN(ev.target.value as unknown as number)) {
                setTextField(ev.target.value as string);
            }
        },
        // eslint-disable-next-line react-hooks/exhaustive-deps
        [value]
    );

And here very important point: setTextField is defined in ancestor component (setTextField sets regular state created with useState) Why? I need a way to make this setTextField available in other component B (to clear input; what is side activity for component B, but anyway it's a must; I would rather quit debounce and leave this structure). So, setTextField is delivered simply as a prop.

My attempts are like this:

const act = (ev: ChangeEvent<HTMLInputElement>) => {
        if (!isNaN(ev.target.value as unknown as number)) {
            setTextField(ev.target.value as string);
        }
    };

    const debouncedChangeHandler = useMemo(() => {
        const changeHandler = (event: any) => {
            act(event);
        };

        return debounce(changeHandler, 300);
    }, []);

but this is not neither first nor last try. None of them works (by that I mean that typed number is not visible in the text field). I have logged also that ev.target.value in debounced version is undefined. It might be that event after 300 ms does not exist any more — but I am not sure. Any way, have no idea how to fix the issue. Could someone help?

0

There are 0 best solutions below