...

/

Core Concepts: State Watchers and Subscribers

Core Concepts: State Watchers and Subscribers

Learn how to watch a Vuex state and react to any changes.

In some cases, a mutation in the state also causes some other kind of behavior. Think of logins. As soon as a user has logged in to the website, additional data, such as personalized feeds or dashboard data may need to autoload. In these cases, watching the state is an option.

What are watchers?

We can subscribe to any part of the state and execute any function as soon as the state changes. Such a function is called a watcher. We introduce watchers with the store.watch method of our Vuex store. The method takes two arguments—a getter that describes which property to observe and a callback that Vuex should execute. The callback itself takes the output of the getter as an argument.

Press + to interact
import { createStore } from 'vuex'
const state = {
counter: 0
}
const store = createStore({
state
})
store.watch(
// getter
state => state.counter,
// callback
counter => {
if (counter > 10) {
console.log('Larger than 10!')
}
}
)

It’s considered good practice to only watch a single property at a time since the flow of information can get confusing. For example, if we watch multiple properties with the same callback, we often can’t tell which mutation triggered the callback.

Let’s practice. The SPA below has a simple ...