When the function is executed, the error message "obtaining ID

As I attempt to remove items from a group and automatically delete the group if there are no items left, I encounter an error in Vue indicating that 'id' is not defined. This seems puzzling to me because it should have already completed the operation.

The error only appears when the group is deleted due to having 0 items remaining in the array - this doesn't occur if I manually delete a group.

Could this be a runtime issue? I am uncertain about the cause.

vue.js:634 [Vue warn]: Error in v-on handler: "TypeError: Cannot read property 'id' of undefined"

(found in <Root>)
warn @ vue.js:634
logError @ vue.js:1893
globalHandleError @ vue.js:1888
handleError @ vue.js:1848
invokeWithErrorHandling @ vue.js:1871
invoker @ vue.js:2188
original._wrapper @ vue.js:7547
vue.js:1897 TypeError: Cannot read property 'id' of undefined
    at Vue.leaveExclusionGroup (index.html:764)
    at click (eval at createFunction (vue.js:11649), <anonymous>:3:4956)
    at invokeWithErrorHandling (vue.js:1863)
    at HTMLSpanElement.invoker (vue.js:2188)
    at HTMLSpanElement.original._wrapper (vue.js:7547)

The function I am using involves checking an array of students and removing them by their IDs onclick, followed by removing the group from the list of groups if there are none left in the group.

I'm baffled as to why 'id' is coming up as undefined since the function should only run again after selecting a student.

Below is the method being used:

 leaveExclusionGroup: function(groupID, studentID){
                        let index = this.exclusionGroups[groupID-1].students 

                        for(var i = 0; i < this.exclusionGroups[groupID-1].students.length; i++){
                            if( index[i].id === studentID){
                                index.splice(i,1)
                            }

                            if(this.exclusionGroups[groupID-1].students === undefined || this.exclusionGroups[groupID-1].students.length === 0){
                                this.removeExclusionGroup(groupID)
                            }
                        }                        
                    },

Here is the method for removing an exclusion group once all students are removed:

  removeExclusionGroup: function(id){

                   console.log(id)
                   for(var i = this.exclusionGroups.length - 1; i >= 0; i--) {
                        if(this.exclusionGroups[i].id === id) {
                            this.exclusionGroups.splice(i, 1);
                            console.log(this.exclusionGroups)
                            }
                        }  
                        this.isHidden = false      
                    },

                    displayModal: function(){
                        $('#myModal').modal('show')
                    },

Answer №1

Make sure to utilize the index array within your for loop to prevent any confusion and place the splice call at the conclusion of the for block:

removeExclusionGroup: function(groupID, studentID){
  let index = this.exclusionGroups[groupID-1].students //this is an array

  for (var i = index.length - 1; i >= 0; i--){
    console.log(index[i])

    if(index === undefined || index.length === 0){
      console.log('execute remove')
      this.removeExclusionGroup(groupID)
    }
    if( index[i].id === studentID){
      index.splice(i,1)
    }
  }                        
},

I believe you may be accessing the index array after splicing, leading to a potential error upon completing the for loop.

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

What is the conventional method for sending data by utilizing the output of a previous data submission in Node.js with Express and FaunaDB?

I am in the process of revising a project and have a question about how to post an array of data using the return value of a previous post request as the ID. Here is an overview of the data structure: Checklist A [ChecklistItem 1, ChecklistItem 2, Checkli ...

What is the most efficient way to switch perspectives?

I'm currently utilizing storybook to simulate various pages of my application. My concept involves encapsulating storybook within one context for mock data, and then during live application execution, switching to a different context where data is fet ...

What is the best way to create separate HTML and component files within Vue.js?

Is it possible to separate HTML and component code into two different files in Vue.js, similar to Angular's structure? ...

Is there a method to verify the presence of a message event listener already?

Is there a method to determine if a message event listener is already in place? I am trying to accomplish something similar to this: if(noMessageEventListenerExists) { globalThis.addEventListener('message', async function (data) {}) } I have ...

Error: Unable to locate module: "./library". The parent module directory is "/"

I keep encountering an issue in my project when attempting to load a module. Whenever I try to import it from the node_modules folder, I receive the following error: Uncaught Error: Module not found: "./MyLibrary". Parent module folder was: "/" However, i ...

Delete the element that was generated using jQuery

Is there a way to add and remove an overlay element using JavaScript? I am struggling to get JavaScript to remove an element that was created with JavaScript. Any suggestions? Check out this JS Fiddle example Here is the HTML code: <div id="backgroun ...

Solving the Issue of Assigning a Random Background Color to a Dynamically Created Button from a Selection of Colors

Trying to create my own personal website through Kirby CMS has been both challenging and rewarding. One of the features I'm working on is a navigation menu that dynamically adds buttons for new pages added to the site. What I really want is for each b ...

Reducing load times in a Vue CLI project

Is it possible to incorporate a less file into my vue-cli project I created? I'm questioning if this is the recommended approach. In the past, I globally added webpack and set up a watcher with a webpack.config.js. However, this time I used vue-cli ...

Implementing route prefix in a combination of express and react deployment

I'm currently facing a challenge while trying to deploy a react app that utilizes router functionality with express. The react app is expected to be accessible via the /dashboard route. At first glance, everything seems to be working smoothly on the ...

Should I generate an array or pull data directly from the database?

Hey there, I've got this JavaScript app and could really use some input or tips. Here's the idea: Users log in to try and defeat a 'boss', with each player working together in the game. Let's say the 'boss' has 10 millio ...

Having trouble selecting all checkboxes in the tree using angular2-tree when it first initializes

My goal is to have all checkboxes auto-checked when clicking the "feed data" button, along with loading the data tree. I've attempted using the following code snippet: this.treeComp.treeModel.doForAll((node: TreeNode) => node.setIsSelected(true)); ...

Having trouble getting a Mocha test to display two decimal places in Javascript? Both Big and Decimal libraries are causing issues

After encountering an error with the Big library, I decided to switch to Decimal. First, I ran npm install Decimal Then, I added the following code: const Decimal = require('decimal'); Even after following the examples, my comparison returned { ...

Tips for retrieving the ID of a dynamic page

In my Higher Order Component (HOC), I have set up a function that redirects the user to the login page if there is no token. My goal is to store the URL that the user intended to visit before being redirected and then push them back to that page. However, ...

Utilizing Json data with Jquery for dynamically placing markers on Google Maps

Seeking assistance as I am currently facing a problem where I need to loop through JSON data and add it as markers on Google Maps, but unfortunately, it only returns null value. Is there a way to automatically connect this to JSON? My plan is to have a Gr ...

Reloading data in Angular using jQuery DataTables

After successfully implementing the jQuery datatables library, I encountered an issue where new data retrieved from my API was not displaying inside the datatable as expected. Instead, it was being shown below the table using ng-repeat. It seems that the d ...

Having trouble with Vue component not updating Vuex state before it loads?

At times, the token is committed to Vuex store while other times it is not. userLogin() { axios.post('api/login', this.logindata,) .then(response => { let token = JSON.parse(localStorage.getItem('token')); t ...

Can you explain the distinction between the "DOMContent event" and the "load event"?

Within Chrome's Developer tool, there is a blue vertical line marked "DOMContent event fired", as well as a red line labeled "load event fired". Is it safe to assume that the "DOMContent event fired" signifies the initiation of inline JavaScript execu ...

The compatibility issue between styled-components and create-react-library is causing some functionality to

Upon attempting to import styled-components into a create-react-library module, I encountered an error message: Error: 'typeOf' is not exported by node_modules\react-is\index.js, imported by node_modules\styled-components\dist ...

The slider thumb is not showing up properly on Microsoft Edge

Hey there! I'm experiencing an issue with the range slider's thumb display in Microsoft Edge. It appears to be positioned inside the track rather than outside as intended. Take a look at this snapshot for clarification: https://i.stack.imgur.co ...

Error: The database has encountered a duplication error in the followers index of the MERNSM.users collection, with a duplicate key value of undefined

Encountered a MongoServerError: E11000 duplicate key error collection: MERNSM.users index: followers_1 dup key: { followers: undefined }. This is puzzling as there is no unique constraint set in my schema. I am unsure of what could be causing this issue, e ...