Debouncer
Debounce a search input so API calls fire only after the user stops typing.
Search component
#[component]
fn SearchBox() -> View {
let query = use_signal(String::new());
let results = use_signal(Vec::<String>::new());
use_debounce(&query, 300, move |q| {
if q.len() >= 2 {
// In production: call #[server] search action
results.set(vec![format!("Result for {q}")]);
}
});
view! {
<div class="search">
<input
type="search"
placeholder="Search…"
onInput={ js! {
state.query.set(event.target.value);
}}
/>
<ul>
{results.get().iter().map(|r| view! {
<li>{r.clone()}</li>
}).collect::<Vec<_>>()}
</ul>
</div>
}
}How it works
use_debounce watches the signal and delays the callback. On SSR the callback runs once; on the client the runtime applies the delay before re-firing.