Watchers vs Computed [Question]
Closed this issue · 1 comments
2manypistachios commented
What are the strict differences / when should I use which?
Can watchers be made to watch two specific states?
Is computed just re-run when ANY of the states change?
Thanks!
Diablow commented
Hi,
Computed properties are intended to store values that depend on one or multiple store properties, their value derivates from other properties and only when a dependency is updated the value is re-calculated. Usage:
const useListStore = create((set, get) => ({
users: [],
async fetchUsers() {
const dbUsers = await fancyWayToGetUsers();
set({ users: dbUsers })
}
}, {
computed: {
admins() {
return this.users.filter(user => user.roles.includes("ADMIN"))
}
}
}));
On the other hand, Watchers are callbacks that trigger whenever a property is updated and you can run any side effect inside them. You have access to the new and previous values, get and set functions are also available in their scope. Usage:
const useListStore = create((set, get) => ({
users: [],
async fetchUsers() {
const dbUsers = await fancyWayToGetUsers();
set({ users: dbUsers })
}
}, {
computed: {
admins() {
return this.users.filter(user => user.roles.includes("ADMIN"))
}
},
watchers: {
users(newValue, oldValue) {
if (newValue.length === 10 && oldValue.length < 10) {
// Do something interesting...
// get & set functions are available in `this` object: this.get() and this.set()
}
}
}
}));