I've encountered an issue with vuex getters while working on my project. I have a route that showcases all users, and upon visiting this route, the AllUsers.vue component is displayed.
Within this component, I'm utilizing the UsersList.vue component, which contains the SingleUser.vue component to exhibit user details.
To fetch all user data from the backend API, I've implemented an action and committed mutations to alter the state. Additionally, vuex modules are being used.
VUEX action:
async setUsers(context) {
const response = await axios.get(`/api/users`);
context.commit('setUsers', response.data.data);
}
VUEX mutation:
setUsers(state, payload) {
state.users = payload;
},
VUEX getter:
allUsers(state) {
return state.users;
},
The action has been dispatched in my App.vue component within the created()
lifecycle hook.
async created() {
await this.$store.dispatch("user/setUsers");
},
However, when attempting to retrieve data from the vuex store using getters, a problem arises.
selectedOptions() {
const selectedUser = this.$store.getters["user/allUsers"].find(
(user) => {
return user.username === this.currentUsername;
});
const selectedRole = selectedUser.roles.find(
(role) => {
return role.name === this.currentUserRole;
}
);
return selectedRole
}
This computed property triggers an error: "
Uncaught (in promise) TypeError: Cannot read property 'roles' of undefined
".
Another getter retrieves a single user object.
singleUser(state) {
return (username) => {
const selectedUser = state.users.find((user) => {
return user.username === username;
});
return selectedUser;
};
},
A computed property is employed to invoke this getter.
singleUser() {
return this.$store.getters["user/singleUser"]("john");
},
Displaying the entire object in the template using the singleUser
computed property yields no errors. The browser presents the following result.
{ "_id": "5fdf4d54c618942e280cf5d8", "name": "John","image": "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9Gc", "username":"john" "__v": 0 }
However, once attempting to display the User name or any other property in the template via singleUser.name
, the browser encounters an error. Initially, it functions correctly but crashes when the page is refreshed.
Uncaught (in promise) TypeError: Cannot read property 'name' of undefined
What could be causing this issue?
Your assistance in resolving this matter would be greatly appreciated. Thank you for taking the time to help.