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

Display overlay objects specifically focused around the mouse cursor, regardless of its position on the screen

I am currently working on a project using SVG files and processing.js to develop a unique homepage that incorporates both animation and static elements. The concept is to maintain the overall structure of the original homepage but with varying colors, esse ...

Enhance Your Form Validation with jQuery UI Dialog Plugin

Currently, I am utilizing the bassistance validation plugin for form validation. I have set up a pop-up modal dialog box to contain a form that requires validation, but for some reason, the form is not getting called. I have checked all my ID's and re ...

Getting the final element in Selenium Webdriver with JavaScript

When I create a script to confirm the successful addition of an element, I always find that the added element is positioned at the end of the page or becomes the last element in a different div. In this case, I am utilizing selenium webdriver and javascrip ...

Modifying an HTML list item to become 'active' in a navigation bar

One way I've been implementing my navbar on each page is by using the following code at the bottom of the page within script tags: $("#navbar-partial").load("navbar.html). The code for the navbar list looks like this: <ul id="main-nav" class="nav ...

The parameter did not successfully transfer to the internal function within Firebase Cloud Functions

I am currently working on a Firebase cloud function that looks like this: exports.foo = functions.database .ref("/candidates/{jobTrack}/{candidateId}") .onCreate((snap, context) => { const candidate = snap.val().candidate; const jobTrack = ...

Preventing audio from being muted using JavaScript requires the removal of audio tags through a MutationObserver

I attempted to utilize the script below to eliminate all audio from a specific website: // ==UserScript== // @name addicto // @namespace nms // @include http://* // @include https://* // @version 1 // @grant none // ==/UserScrip ...

The MUI multiple select feature is experiencing issues following the addition of a new button

I'm having trouble adding buttons below a select dropdown menu with a specific height. When I try to put the menu item inside a div, the multiple select stops working and I have no idea why. Can someone help me figure this out? Check out my CodeSandb ...

Iterating through a JSON array using the JQuery .each method

Greetings! I'm trying to figure out how to access the msg -> items using jQuery's .each() method. { "msg": [ { "msg_id": "18628", "msg_userid": "12", "msg ...

Ways to compare UTC timestamps using JavaScript

Insight into Time Data I have obtained UTC start and end times from a database query, which are stored in an array format as follows: [ '9145001323', '08:00', '12:00' ] The second and third elements in the array indicate t ...

Executing two AJAX requests simultaneously with Django, AJAX, and jQuery in a single event

I believe I'm on the right track to getting this to work, but I could really use some assistance with the JQuery aspect. It seems that everything functions as expected after the second click onwards, but there is an issue with the functionality on the ...

Express API encounters an issue with multer and body-parser as req.file is undefined

I am in the process of developing an API that will need to handle file uploads along with other GET and POST requests. To manage file uploads, I am using 'multer' while utilizing 'body-parser' for all other HTTP requests. My goal is to ...

Strategies for simplifying this extensive if/else block

My current if/else statement in React Native is functional but seems verbose. I am curious to know how other developers would optimize and shorten it. I feel like my code represents a beginner's approach, and I welcome suggestions on how to improve i ...

The issue with hiding and showing elements using JavaScript during drag and drop functionality

In my code, I have two boxes with IDs box1 and box2, These boxes can be dragged and dropped into the boxleft element, Upon dropping them, the background image is removed and only the name appears in the box, My issue is that when loading values into box ...

How can you replicate a mouseover event using Selenium or JavaScript?

I have recently been working on a task involving web UI automation using Selenium, Javascript and SeLion. My goal is to capture a screenshot of a scenario similar to the Google homepage, specifically focusing on the "Search by voice" feature when hovering ...

`Shifting a spherical object from point A to point B along its axis`

I am currently working on a project that involves rotating a sphere from point A to point B on itself. After finding Unity3d code for this, I came across the following solution: Quaternion rot = Quaternion.FromToRotation (pointA, pointB); sphere.transform ...

Guide on implementing enums (or const) in VueJS

Seeking help on a seemingly simple task, I am trying to understand how to use "enums" in VueJS. In my file named LandingPage.js, I have the following code: const Form = { LOGIN: 0, SIGN_UP: 1, FORGOT_PASSWORD: 2, }; function main() { new Vue({ ...

Experience a seamless transition to the next section with just one scroll, allowing for a full

I've been attempting to create a smooth scroll effect to move to the next section using Javascript. However, I'm encountering issues with the window's top distance not being calculated correctly. I'm looking to have the full screen div ...

Leverage the power of react-i18next in class-based components by utilizing decorators and Higher Order

Currently, I am working on implementing i18n into my React project that also utilizes Redux, with the assistance of react-i18next. In this particular project, we are using class components alongside decorators. Originally, I intended to experiment with r ...

Vue3 compilation error: Every single file component must include at least one <template> or <script> block

Attempting to update a large existing codebase from Vue2 to Vue3 with the help of Webpack. I have successfully upgraded the necessary packages in package.json, which now looks like this (no issues encountered): "vue": "^3.2.45", "@vue/compat": "^3.2.45", " ...

Filtering JSON data by date range in React JS

I have a dataset with JSON data containing ISO dates, and my goal is to filter out entries based on the "date_created" field falling within a specific date range. The time component should be ignored in this comparison, and the original JSON data should re ...