I set up debounce inside my functional component like this:
const debouncedFunc= debounce(myFunction, 500);
I have the below TextField
<TextField
id="myField"
maxLength={8}
onChange={(e) => debouncedFunc(e.target?.value)}
/>
I have the myFunction like this
function myFunction(val) {
if (val.length === 8) {
console.log(val);
}
}
So this works well. It prints value when a user types eight characters into the field. The problem is that I need to empty the value in this field when a user types eight characters, and debounced function does kick in. Normally, TextField, I can empty the value in the field by e.target.value="". Since I am in the debounce function, I do not have a reference to the e, so I cannot empty it.
Long question short, what is the best way to empty the textfield from a debounce function?
My current and only solution is this, anyone that can think of a better solution please do share
export default function DebounceFeaturedTextfield() {
const debouncedFunc= debounce(myFunction, 500);
let TextFieldRef = "";
function myFunction(val) {
if (val.length === 8) {
TextFieldRef.setInputValue("");
}
}
return (
<TextField
ref={(r) => {
TextFieldRef = r;
}}
id="myField"
maxLength={8}
onChange={(e) => debouncedFunc(e.target?.value)}
/>
);
}