Watchers

Learn how to watch for global state changes.

Alpine provides a handy $watch function that allows you to watch for state changes on a component. Spruce also offers a similar API that allows you to watch for state changes on any store.

Registering a watcher

To register a new "watcher", use the Spruce.watch() method.

Spruce.store('user', {
    name: 'Ryan Chandler',
    email: 'support@ryangjchandler.co.uk',
})

Spruce.watch('user.name', value => console.log(value))

The first argument is the "dot notation" of the property's path. In the example above, the watcher is being registered on the user store and looking at the name property, therefore the dot notation of this path is user.name.

The second argument is a callback function that will be invoked each time the property being watched is mutated. This callback receives the new value of the property, meaning you don't need to reach into the store to grab it.

Be careful when registering watchers that mutate other store properties. These mutations can create infinite loops.

Using `$watch`

In newer versions of Alpine, you can watch for changes on magic properties using $watch. This is useful if you only want to watch for state changes to a global store from a single component.

The watcher must be registered inside of the x-init directive on the component.

<div x-data x-init="$watch('$store.user.name', () => ...)">
    <!-- markup -->
</div>

The first argument to $watch must be a string. When watching a store, you must use the name of the property as accessed inside of other directives.

In the example above, the watcher is being registered on the user store, looking for changes of the name property.

Watchers registered using $watch will not be invoked when a global store is modified outside of the component where the watcher is being registered.

Last updated