Tuesday, June 4, 2024
 Popular · Latest · Hot · Upcoming
122
rated 0 times [  128] [ 6]  / answers: 1 / hits: 9770  / 3 Years ago, mon, july 19, 2021, 12:00:00

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


More From » vuex

 Answers
3

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.


[#1089] Saturday, July 10, 2021, 3 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
anais

Total Points: 672
Total Questions: 118
Total Answers: 121

Location: Oman
Member since Fri, Dec 23, 2022
1 Year ago
anais questions
Fri, Jul 29, 22, 00:00, 2 Years ago
Tue, May 11, 21, 00:00, 3 Years ago
Fri, Apr 2, 21, 00:00, 3 Years ago
;