I'm trying to understand the purpose of composables. I have a simple composable like this and was trying to watch state from a Pinia store where the watch
does not trigger:
import { ref, watch, computed } from "vue";
import { storeToRefs } from "pinia";
import useFlightsStore from "src/pinia/flights.js";
import usePassengersStore from "src/pinia/passengers.js";
export function useFlight() {
const route = useRoute();
const modalStore = useModalStore();
const flightsStore = useFlightsStore();
const { selection } = storeToRefs(flightsStore);
const passengersStore = usePassengersStore();
const { passengers, adults, children, infants } =
storeToRefs(passengersStore);
watch([adults, children, infants], (val) => console.log('value changes', val))
Where as the same thing in a Vue component works as expected.
So we cannot watch values inside composables?
I think you can watch values inside composables.
But, to watch a pinia state it has to be inside an arrow function:
watch(() => somePiniaState, (n) => console.log(n, " value changed"));
It's like watching a reactive object.
I believe this should be documented better. In Pinia documentation we can read how to watch the whole store or how to subscribe to a store but not how to watch a single state property inside a component or composable.
Also, the docs are somewhat shy in explaining that you can watch a property inside a store using setup()
way of describing a store.
More on this here: https://github.com/vuejs/pinia/discussions/794#discussioncomment-1643242
This error also silently fails (or does not execute), which is not helpful...
I needed to watch a specific state attribute in one of my components but I didn't find my use case on the official documentation . I used a mix between a watch and storeToRefs to do it.
import { usePlaylistsStore } from '@/stores/playlists'
import { storeToRefs } from 'pinia'
export default {
name: 'PlaylistDetail',
setup() {
const playlistsStore = usePlaylistsStore()
const { selectedGenres } = storeToRefs(playlistsStore)
return { selectedGenres }
},
watch: {
selectedGenres(newValue, oldValue) {
// do something
}
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.