I'm attempting to retrieve information from my vuex store, however, encountering an error in the process

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.

Answer №1

In my opinion, the getter allUsers is essentially similar to state.users. It might be beneficial to set the default value of allUsers to an empty array.

const selectedUser = this.$store.getters["user/allUsers"].find(
     (user) => {
          return user.username === this.currentUsername;
     }); // it seems that this.currentUsername is not defined in vuex, causing
    // Uncaught (in promise) TypeError: Cannot read property 'roles' of undefined

I recommend utilizing vue devtools for examining its data flow in order to resolve the issue.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Unlocking the Power of $http and Stream Fusion

I'm interested in accessing the public stream of App.net. However, when I attempt to retrieve it using a simple $http.get(), I only receive one response. $http .get('https://alpha-api.app.net/stream/0/posts/stream/global') .success(func ...

What are the best ways to make this date more visually appealing and easy to understand?

Hey there! So I have a date that looks like this: 2022-06-28T17:09:00.922108+01:00 I'm trying to make it more readable, but unfortunately, when I attempted using moment-js in my javascript/react project, it threw an error stating "invalid format". ...

Troubleshooting: Issue with Updating Views in Angular JS

I've been attempting to change the view from the controller, but it's just not working properly. app.js var app = angular.module('vla', ['ngRoute']); app.config(function ($routeProvider){ $routeProvider ...

Signing up for Django with a phone number

Currently, I am working on a Django project with Django REST on the backend and Vue.js on the client side. My goal is to implement phone number registration and login functionality. If anyone has done this before, I would appreciate any advice or guidance ...

What are the most effective strategies for managing vast amounts of data using JS fetch?

The server is taking about 2 minutes to export a large JSON data, resulting in a timeout error on the client side before receiving a response from the server. I have searched online for solutions, but I cannot find a way to extend the timeout or continue ...

Having difficulty toggling a <div> element with jQuery

I am attempting to implement a button that toggles the visibility of a div containing replies to comments. My goal is to have the ability to hide and display the replies by clicking the button. The "show all replies" button should only appear if there are ...

The issue with EJS Header and Footer not showing up on the

I am currently building a basic todo list application using EJS. However, I am encountering an issue when running it. I would like to run app.js with the header and footer in EJS, but it seems that it is not recognizing the header despite using what I beli ...

The Angular modal service is failing to show up on the screen

I am having trouble implementing the angular modal service in my web application. When I click on the button, the modal does not appear. Can someone help me figure out what I am doing wrong? Builder View <div ng-controller="BuilderController as vm"> ...

how to prevent autoscrolling in an angular application when overflow-x is set to

In my socket event, I am using $scope.items.unshift(item) to place the new item at the top of the list. The html code includes <ol ng-repeat="item in items"><li>{{item.name}}</li></ol> An issue arises when a new item is added whil ...

What issue is being encountered with this JavaScript generated by PHP?

PHP on the host generates JavaScript code that results in an error stating: missing ; before statement The generated JavaScript code looks like this: try{ obj = document.getElementById('subcat'); }catch(e){} try{ obj.innerHTML = ...

Issue with conflicting trigger events for clicking and watching sequences in input text boxes and checkboxes within an AngularJS application

When creating a watch on Text box and Check box models to call a custom-defined function, I want to avoid calling the function during the initial loading of data. To achieve this, I am using a 'needwatch' flag inside the watch to determine when t ...

Having trouble retrieving JSON data using ajax

I am currently working with JSON data that is being generated by my PHP code. Here is an example of how the data looks: {"Inboxunreadmessage":4, "aaData":[{ "Inboxsubject":"Email SMTP Test", "Inboxfrom":"Deepak Saini <*****@*****.co.in>"} ...

Retrieve the file using React and receive it through Express

Despite trying several solutions on SO, none have been successful for me thus far, so I kindly ask for your patience. In React front-end, the user initiates a file download request with some variables to the backend: const data = text.value; fetch(" ...

Vuex: mutation type 'dropdownState' is not recognized

As a beginner, I am trying to learn something new. Currently, I am working with Vue.js 2 and facing an issue with Vuex. My goal is to add an active class and display the content of a dropdown when the div is clicked. However, I encountered the following er ...

Loopback: Unable to access the 'find' property as it is undefined

I've come across a few similar questions, but none of the solutions seem to work for me. So, I decided to reach out for help. I'm facing an issue while trying to retrieve data from my database in order to select specific parts of it within my app ...

What is the best way to create an Office Script autofill feature that automatically fills to the last row in Excel?

Having trouble setting up an Excel script to autofill a column only down to the final row of data, without extending further. Each table I use this script on has a different number of rows, so hardcoding the row range is not helpful. Is there a way to make ...

Combining Django Templates and Vue.js

I am currently working on integrating Vue components into Django templates. The initial setup went smoothly, however, I am facing an issue with a component that requires its own import. Here is the component (vue/dropdown.html): <div id="app" ...

Error encountered: Attempting to render an object as a react component is invalid

I am attempting to query data from a Firestore database. My goal is to retrieve all the fields from the Missions collection that have the same ID as the field in Clients/1/Missions. Below, you can find the code for my query: However, when I tried to execu ...

"Enhance User Experience with jQuery Autocomplete using String Arrays

Within my web form model (AdtFormModel), there is a variable: public List<String> TemoinsVille { get; set; } I opted for a list structure as I intend to allow users to dynamically add more 'TemoinsVille' inputs in the form. Currently, ...

JQuery class for swapping elements upon scrolling

I am currently working on a navigation bar that changes classes to create a fading effect for the background. The approach I have taken involves targeting the window itself and monitoring the scroll position of the user. If the user scrolls down more than ...