vue component doesn’t update after state changes in pinia store

storeToRefs()

You need to use storeToRefs() to extract properties from the store while keeping those properties reactive.

import { storeToRefs } from 'pinia'
const themeStore = useThemeStore();
const { isDark } = storeToRefs(themeStore);

Computed property

Thanks to @Fennec for suggesting the computed way of getting reactive state. Although I don’t recommend this method since there is a dedicated storeToRefs() available.

import { computed } from 'vue'
const themeStore = useThemeStore();
const isDark = computed(() => themeStore.isDark);

WRONG ways to get reactive state from the Pinia store:

All the ways listed below of getting the state (properties, getters) from the Pinia store are WRONG:

import { useThemeStore } from "./stores/theme.js";
const themeStore = useThemeStore();

// WRONG ways of extracting state from store
let isDark = themeStore.isDark; // not reactive
let isDark = ref(themeStore.isDark); // reactive, but will not be updated with the store
let { isDark } = themeStore; // not reactive, cannot destructure

Destructuring actions directly from the store.

Its worth to note here that “you can destructure actions directly from the store as they are bound to the store itself.” (docs)

If you have an action named “increment” in your store, you can just extract it directly from the store in your component:

...
const { increment } = store // actions can be destructured directly
...

Also, according to Pinia docs, the first argument is the unique ID, so you do not need to specify the id again inside the options object. Or you can just ignore the first argument and just specify the id as an option. Either way is fine.

Leave a Comment