When working with computed properties using data fetched by the mapGetters function in my Vuex store, I always encounter the issue of getting an undefined value until the entire page or DOM is fully loaded.
For instance, I have an example of an isRegistered computed property that determines whether to hide or display certain buttons:
computed: {
...mapGetters(['solos', 'user']),
isRegistered () {
return this.solos.registered.indexOf(this.user._id) !== -1
}
}
Below is the HTML code for buttons utilizing the isRegistered computed property:
<a href="#" class="register-button" v-if="!isRegistered">REGISTER NOW</a>
<a href="#" class="registered-button" v-if="isRegistered">REGISTERED</a>
I set the getters through an action called within the created hook:
created () {
this.getTournament('solos').catch(err => {})
}
Here is the action responsible for setting the corresponding getters:
getTournament: ({commit}, type) => {
return feathers.service('tournaments').find({
query: {
type: type,
status: 'registering'
}
}).then(tourney => {
commit(type.toUpperCase(), tourney.data[0])
})
}
And here's the associated mutation and getter:
const mutations = {
SOLOS (state, result) {
state.solos = result;
}
};
const getters = {
solos (state) {
return state.solos
}
}
The problem arises when the value initially shows up as undefined before the PAGE/DOM is fully loaded, leading to the following error related to .indexOf:
TypeError: Cannot read property 'indexOf' of undefined
Currently, I've resorted to using an if statement within the computed property to check if the state data has been loaded yet:
isRegistered () {
if (this.solos._id) return this.solos.registered.indexOf(this.user._id) !== -1
}
This workaround doesn't feel like the ideal approach. Is there something incorrect in my implementation?