Search code examples
javascriptvue.jsvuejs2vuexvuejs3

Passing Reactive State from Vuex to Composable


I'm working on a composable that's meant to encapsulate some logic with Vue3 and Vuex. The composable is working with a "feed" that is liable to change in the future, and comes from Vuex.

I'd like the composable to return the status of that feed when the feed changes as a computed value.

However, I'm unclear on how to fetch/wrap the value from Vuex so this computed property will change when the value in Vuex changes. For instance, at the top of the composable, I'm passing in the ID of the feed, fetching it from Vuex, and then using it in the composable like this:

const feed = store.getters['feeds/getFeedById'](feedId)

I'm then using the feed in a computed, inside of the composable, like this:

const feedIsReady = computed(() => feed.info.ready ? 'READY' : 'NOT READY')

However, when I change the feed object in Vuex via a mutation elsewhere in the application, the feed inside the composable does not change.

I've tried wrapping the feed in a reactive call and it's individual properties with toRefs but those approaches only provide reactivity within the composable itself, and don't capture changes from Vuex.

How would one wrap the feed from Vuex to provide reactivity? I need the changes in Vuex to propagate to my composable somehow.


Solution

  • Did you try to use vuex getter in your composable with computed property:

    const feed = computed(() => store.getters['feeds/getFeedById'](feedId));