Explain Codes LogoExplain Codes Logo

How to watch store values from vuex?

javascript
vuex-store
reactivity
state-management
Alex KataevbyAlex Kataev·Sep 18, 2024
TLDR

Achieving Vuex store observation is as easy as combining the watch function and computed for reactive state tracking. Here's sample code using Vue 3:

import { computed, watch } from 'vue'; import { useStore } from 'vuex'; const store = useStore(); // Get your Vuex "remote control" const storeValue = computed(() => store.state.someValue); // Tune into `someValue` watch(storeValue, (newVal, oldVal) => { console.log(`Hey there! Store value changed here: ${oldVal} -> ${newVal}`); // Report any change in 'channel' });

Abracadabra! You are now watching someValue in your Vuex store.

Vuex Store watching: In-depth analysis

Vuex provides powerful ways to track changes, but there are certain techniques that brings out the true 'Jedi' in Vuex reactivity. Let's do some scripting:

Calculated tracking with getters

Computed properties with Vuex getters is like a ninja ready to respond to any change in the store. It's good to keep ninjas in check, for the sake of code neatness!

import { computed } from 'vue'; import { mapGetters, useStore } from 'vuex'; export default { computed: { ...mapGetters(['fruitBasket']), fruitCountVisible() { // Our ninja fruit basket viewer return this.fruitBasket; } } };

Tracking changes with watch

Now we need a yell to indicate when things change. A good place for such yells is inside the created lifecycle hook.

export default { created() { this.$store.watch( (state) => state.fruits, (fruits) => { console.log('Fruit-maggeddon occurred! Fruits have changed.', fruits); } ); } };

State tracking at its best

Got nested data changes? No worries! Bring on the deep watchers:

watch( () => store.state.nestedData, (newValue) => { // Handle the deep state change like a boss }, { deep: true } );

Vuex store: State management & reactivity

Vuex forms the backbone of state management. Keep your Vuex spine healthy with these tips:

Avoid repetition

Let Vuex getters do the grunt job of carrying state variables, not local watchers. Vuex is at your service!

Mutations and actions for the win

All mutations please stand up! Only state changes allowed here. For the complex stuff, actions stay back to crack the harder nuts.

// Mutating state in Vuex mutations: { increment(state) { state.counter++; // Going up! } } // Call action in a component methods: { makeCounterSkyrocket() { // Fly, counter, fly! this.$store.dispatch('increment'); } }

Non-modularized state?

Directly tapping into state variables is as simple as $store.state.variableName.

Vuex best practices and possible caveats

Sure, Vuex pretty much rules the Vue kingdom but it does have a few wild beasts. Here's how to tame them:

Watch your watchers!

Be cheeky with your watchers, especially deep ones. Too many, and you might get performance hiccups!

Modular stores

In modular Vuex stores, paths have to be more specific and you may need to namespace getters/actions.

Power your reactivity

Vue isn't psychic, it can't detect changes in array indices or sneakily added/removed object properties. For these scenarios, Vue provides Vue.set and Vue.delete.