I am working on an application that heavily relies on Vue-Router and Vuex for state management.
Within the Dashboard component, important user information is displayed. This data is fetched asynchronously from a database by Vue and then stored in Vuex.
The issue arises when subcomponents try to access this user information from the Store during their initial load. Sometimes, the user entry in the store is empty leading to a TypeError
: $setup.user is null.
One common workaround is to add a v-if
directive in front of each HTML element which can become quite cumbersome and inefficient in the long run.
Is there a better way to address this problem without littering the code with multiple v-if
checks?
User.vue:
<template>
<div>
<div id="profile_content">
<UserNavbar />
<router-view :key="$route.fullPath" />
</div>
</div>
</template>
UserDashboard:
<template>
<div>
<ProfileInformationCard>
<span v-if="user">{{ user.name }}</span>
<span v-if="user">{{ user.lastLogin }}</span>
</ProfileInformationCard>
</div>
</template>
<script>
import _ from "lodash";
import { useStore } from "vuex"
import { watch } from "vue"
export default {
setup(){
const store = useStore()
const user = store.state.user.currentUser
watch(() => _.cloneDeep(store.state.user.currentUser), () => {
user.value = store.state.user.currentUser;
}
);
}
}
</script>