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

Viewed 6523

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

1 Answers

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.

Related