So I’m trying to update a quantity counter optimistically when you click the increment or decrement buttons. This part works fine with useOptimistic, however I don’t want the server action to get executed for every quick click on those increment/decrement buttons. I want to debounce the server action so that it will only execute after a set delay between the fast clicks. Is that possible without having to give up on using useOptimistic?
<form
action={async () => {
// use useOptimistic to increment quantity state in parent
updateQuantity(1)
// server action that updates the cart with the quantity
// if I quickly click on the increase quantity button this
// function will be fired many times quickly. I don't want
// the below server action to run more than eg. 300 ms after
// THE LAST click. So how do I debounce this server action call?
await action();
}}
>
Someone suggested I could skip the form
tag with the action
attribute and even skip useOptimistic
and do something like this:
const debouncedSearch = useDebounce(quantityCounter, 300); // time in ms
useEffect(() => {
myServerAction({cartItemId: "someid", "quantity": quantityCounter}) // example execution
}, [debouncedSearch]);
Then I’d have to roll back the value manually in case the server request failed, which is why I really want to keep using useOptimistic where this is done automatically.
Any suggestions?
Using the latest Next.js 14