I have a form component, and I would like to perform an API request as I am typing. I want to debounce this so I don't spam the server. Here is my code:
export default function MyItem ({ id, name }) {
const debouncePatch = (name) => {
debounce(patchItem.bind(this, id, name), 500)
}
return (
<div>
<form
type='text'
value={name}
onChange={(evt) => debouncePatch(evt.target.value)}
/>
</div>
)
}
The patch item does a simple patch call to the server so that the item's name updates as I am typing. It looks something like this:
export default function patchItem (id, name,) {
return axios.patch(`${MY_BASE_URL}/${id}`, { name })
}
With the debounce it is not working at all. The patchItem
function is never called. How can I fix this?
You're calling
debounce
on every change to theinput
but it just creates a new debounced function every time. You need to create a single debounced function and then use it as event handler. Like this:Also make sure the input gets the
defaultValue
rather thanvalue
so it can be edited.