I tried with:
let searchText = $derived(debounce((typedText) => typedText, 2000)(typedText));
But searchText
is not assigned!
Reproduction with $derived
: searchText
is not assigned.
Reproduction with $effect()
: searchText
assignment is not debounced at all.
A debounce
function must only be called once, otherwise one gets new instances with independent timeouts.
Using an $effect
:
const update = debounce(v => searchText = v, 300);
$effect(() => update(typedText));
The logic could be wrapped to be compatible with $derived.by
:
function debouncer(getter, wait, immediate) {
let current = $state();
const update = debounce(v => current = v, wait, immediate);
$effect(() => update(getter()));
return () => current;
}
let typedText = $state();
const searchText = $derived.by(debouncer(() => typedText, 300));