Watches reactive values and executes a callback whenever those values change.
This function is the synchronous variant of watch.
It will re-execute after every fine grained change, even if those changes occur in immediate succession.
syncWatch
should therefore be considered a low level primitive, for most use cases watch should be the right tool instead.
Example:
const r1 = reactive(1);
const r2 = reactive(2);
syncWatch(
// Selector: reactive code (may be complex, but should be fast).
() => [r1.value, r2.value, r1.value + r2.value],
// Callback: only executes if selector returns different values.
([v1, v2, v3]) => {
console.log(v1, v2, v3);
}
);
syncWatch
returns a handle that can be used to unsubscribe from changes.
That handle's destroy()
function should be called to stop watching when you are no longer interested in updates:
const handle = syncWatch(() => [someReactive.value], () => {
// ...
});
// later:
handle.destroy();
NOTE: You must not modify the parameters that get passed into
callback
.
a function that returns the values to watch.
a function that will be executed whenever the watched values changed.
Optional
options: Omit<WatchOptions<Values>, "dispatch"> & { immediate?: false }additional options.
Use watch with option dispatch: "sync"
instead.
This overload is used when immediate
is not set to false
.
a function that returns the values to watch.
a function that will be executed whenever the watched values changed.
Optional
options: Omit<WatchOptions<Values>, "dispatch">additional options.
Use watch with option dispatch: "sync"
instead.
Deprecated
Use watch with option
dispatch: "sync"
instead.