How to watch a Vuex getter in Composition API (Vue 3)
Asked Answered
B

1

5

The state of my application seems to load AFTER my components get loaded, so my thought was to watch for the state-getter. But how do I watch a Vuex getter in the composition API?

My state & getter:

state: () => ({
    companies: [],
  }),
  getters: {
    getAvailableCompanies(state) {
      return state.companies
    }
  },
  [...]
}

In my module, I import the store:

import { store } from '@/store/store.js'

And get the value of the getter in the setup() function of my component:

const companies = ref(store.getters["companies/getAvailableCompanies"])
console.log("companies", companies)

Now I am trying to watch for changes (also in setup()), once the state is populated:

watch(
  companies, (curr, old) => {
    console.log(curr, old)
  }
)

Unfortunately, companies.value never changes and stays undefined

Belly answered 19/7, 2021 at 8:30 Comment(0)
E
11

Use ref in this case is not correct since AFAIK the value of ref variable is set at the moment you assign and only change when you re-assing its value. For example:

const companies = ref(store.getters["companies/getAvailableCompanies"]);
companies.value = [];

To re-calculate your companies array when the data is ready (changed) in the store, you need to use computed instead.

const companies = computed(() => store.getters["companies/getAvailableCompanies"]);

You can verify by using your watch or see the update in the view.

Equipollent answered 23/7, 2021 at 10:57 Comment(1)
Will have a look at that later. Thanks so farKeratoplasty

© 2022 - 2024 — McMap. All rights reserved.