I have a add-user.vue
component. It is my template for adding a new user and editing a existing user. So on page load I check if route has a id
, if so I load a user from a state array to edit it. My issue is that user
is undefined because the state array users
is empty. How can I ensure that my user object isn't undefined. It does load sometimes but on refresh it doesn't. I thought I had it covered but nope. This is my setup. What am I missing here?
Store
state: {
users: []
},
getters: {
users: state =>
_.keyBy(state.users.filter(user => user.deleted === false), 'id')
},
actions: {
fetchUsers({
commit
}) {
axios
.get('http://localhost:3000/users')
.then(response => {
commit('setUsers', response.data);
})
.catch(error => {
console.log('error:', error);
});
}
}
In my add-user.vue
component I have the following in the data()
computed:{}
and created()
data() {
return {
user: {
id: undefined,
name: undefined,
gender: undefined
}
};
},
computed: {
...mapGetters(['users'])
},
created() {
if (this.$route.params.userId === undefined) {
this.user.id = uuid();
...
} else {
this.user = this.users[this.$route.params.userId];
}
}
Template
<template>
<div class="add-user" v-if="user"></div>
</template>
My User.vue
I have the following setup, where I init the fetch of users on created()
<template>
<main class="main">
<AddUser/>
<UserList/>
</main>
</template>
<script>
import AddUser from '@/components/add-user.vue';
import UserList from '@/components/user-list.vue';
export default {
name: 'User',
components: {
AddUser,
UserList
},
created() {
this.$store.dispatch('fetchUsers');
}
};
</script>
I have tried this. When saving in my editor it works but not on refresh. The dispatch().then()
run before the mutation
setting the users does.
created() {
if (this.$route.params.userId === undefined) {
this.user.id = uuid();
...
} else {
if (this.users.length > 0) {
this.user = this.users[this.$route.params.userId];
} else {
this.$store.dispatch('fetchUsers').then(() => {
this.user = this.users[this.$route.params.userId];
});
}
}
}
created
hook. try usingthis.$store.getters.users
increated
or move ur codes intomounted
hook – Jacob Gohgetters
in created makes no difference, as it is reactive. When thefetchUsers
is done the getters will have value. – Dejan.S