I have a simple form and a field to render the value of that input field from that form
<div id="app">
<form id="form">
<label
>some form
<input type="text" name="myInput" />
</label>
</form>
<p id="field"></p>
</div>
function getFormValues(event) {
const data = new FormData(event.currentTarget);
const { myInput } = Object.fromEntries(data);
console.log("value", myInput);
field.textContent = myInput;
}
const form = document.getElementById("form");
const field = document.getElementById("field");
form.addEventListener("input", getFormValues); //
So far it works. However once I debounce it with this util I wrote (btw I am well aware of utils like lodash
out there that can do the same thing)
function debounce(fn, delay) {
let timerId;
return (...args) => {
if (timerId) clearTimeout(timerId);
timerId = setTimeout(() => {
fn(...args);
}, delay);
};
}
const debouncedGetFormValues = debounce(getFormValues, 500);
form.addEventListener("input", debouncedGetFormValues); // Failed to construct 'FormData': parameter 1 is not of type 'HTMLFormElement'.
All of a sudden I got an error saying that Failed to construct 'FormData': parameter 1 is not of type 'HTMLFormElement'.
Here is the live demo https://codesandbox.io/s/awesome-rosalind-1brqi?file=/src/index.js
Not sure what went wrong here.
Please don't vote to close this question just because event currentTarget changes after setTimeout exists. It doesn't solve my problem. Even if you change
const data = new FormData(event.currentTarget);
to const data = new FormData(event.target);
. The problem is still there.