Function leptos_use::watch_with_options

source ·
pub fn watch_with_options<W, T, DFn, CFn>(
    deps: DFn,
    callback: CFn,
    options: WatchOptions
) -> impl Fn() + Clone
where DFn: Fn() -> W + 'static, CFn: Fn(&W, Option<&W>, Option<T>) -> T + Clone + 'static, W: Clone + 'static, T: Clone + 'static,
Expand description

A version of leptos::watch but with additional options.

§Immediate

This is the same as for leptos::watch. But you don’t have to specify it. By default its set to false. If immediate is true, the callback will run immediately (this is also true if throttled/debounced). If it’s false, the callback will run only after the first change is detected of any signal that is accessed in deps.

let (num, set_num) = create_signal(0);

watch_with_options(
    move || num.get(),
    move |num, _, _| {
        log!("Number {}", num);
    },
    WatchOptions::default().immediate(true),
); // > "Number 0"

set_num.set(1); // > "Number 1"

§Filters

The callback can be throttled or debounced. Please see [watch_throttled] and [watch_debounced] for details.

watch_with_options(
    move || num.get(),
    move |num, _, _| {
        log!("Number {}", num);
    },
    WatchOptions::default().throttle(100.0), // there's also `throttle_with_options`
);
watch_with_options(
    move || num.get(),
    move |num, _, _| {
        log!("number {}", num);
    },
    WatchOptions::default().debounce(100.0), // there's also `debounce_with_options`
);

§Server-Side Rendering

On the server this works just fine except if you throttle or debounce in which case the callback will never be called except if you set immediate to true in which case the callback will be called exactly once when watch() is executed.

§See also

  • [watch_throttled]
  • [watch_debounced] Version of watch that accepts WatchOptions. See watch for how to use.