What could be causing this data attribute error when making Fetch API delete requests?

Working with Express, MongoDB, and EJS, I crafted a function to handle fetch api delete requests. The goal was to reuse this function for multiple delete requests in the application triggered by different buttons. However, it only works the first time it's called. Subsequent calls with other buttons result in the following error:

Uncaught TypeError: Cannot read property 'delete' of undefined
    at delItem (main.js:42)
    at HTMLElement.<anonymous> (main.js:135) 

The key 'delete' is used as the data attribute property to extract the ID from the database upon button clicks. Despite attempts to change the property name or create a new function, the same error persists. Could someone point out where I'm going wrong? This marks my initial experience with the fetch API, and after two weeks of trial and research, I seek assistance. Refer to my code below:

EJS 

<ul id="list">
   <% for(let i = 0; i < list.length; i++) {%>
      <span class="saved-list-item">
          <li class="list-item">
              <div class="checkbox">
                 <span id="circleIcon"><i data-delete="<%= list[i]._id %>" class="far fa-circle uncheck"></i></span>
                     <span id="checkIcon"><i class="fas fa-check-circle check"></i></span>
                                   
              </div>
              <span class="editText"><%= list[i].item %></span>
              <div class="buttons">
                  <button type="submit" data-update="<%= list[i]._id %>" class="saveBtn"><i class="fas fa-edit"></i></button>
                  <button type="button" onclick="window.location.reload()"class="cancelBtn">X</button>
                  <button type="button" data-update="<%= list[i]._id %>" class="editBtn"><i class="fas fa-edit"></i></button>
                  <button type="button" data-delete="<%= list[i]._id %>" class="delItemBtn"><i class="fas fa-trash-alt"></i></button>   
               </div>                
          </li>  
       </span>
    <% } %>
</ul> 


Fetch function (working fine on the delete button)


const delItemBtn = document.querySelectorAll('.delItemBtn');

for(i = 0; i < delItemBtn.length; i++) {
    delItemBtn[i].addEventListener('click', delItem);
};

for(let u = 0; u < delItemBtn.length; u++) {
    delItemBtn[u].addEventListener('click', (e) => {
        e.preventDefault()
        localStorage.removeItem(localStorage.key(u)); // LOCAL STORAGE REMOVE ONE
    })
}

function delItem() {
    
    fetch('/list/' + this.dataset.delete, {
        method: 'delete',
        headers: { 'Content-Type': 'application/json' },
    })
    .then(res => {
        if (res.ok) {
            return res.status(200)
        } else {
            res.status(500)
        }
    })
    .then(window.location.reload())
    .catch(console.error)
};


Trying to trigger the fetch delete request by calling the delItem() function through a different button click event, but encountering issues.

for(let i = 0; i < uncheck.length; i++) {
    uncheck[i].addEventListener('click', (e) => {       
        if(e.target.classList.contains('uncheck')) {           
            check[i].className = 'fas fa-check-circle check';
            check[i].style.display = 'block';
            uncheck[i].className = 'fas fa-check-circle check';
            li[i].style.textDecoration = 'line-through';
            editBtn[i].style.display = 'none';
            delItemBtn[i].style.display = 'none';
            

            // LOCAL STORAGE SAVE 
            savedChecks = document.querySelector('.saved-list-item').innerHTML;
            localStorage.setItem('checkedItems'+ new Date().getTime(), savedChecks);

        delItem() //Intended call for delItem function, causing an error.

        } 
    });
};

Answer №1

To resolve the issue, I implemented a separate event listener within the for loop as shown below:

for(let index = 0; index < uncheck.length; index++) {

    uncheck[index].addEventListener('click', delItem); //Modified code snippet here

    uncheck[index].addEventListener('click', (event) => {       
        if(event.target.classList.contains('uncheck')) {           
            check[index].className = 'fas fa-check-circle check';
            check[index].style.display = 'block';
            uncheck[index].className = 'fas fa-check-circle check';
            li[index].style.textDecoration = 'line-through';
            editBtn[index].style.display = 'none';
            delItemBtn[index].style.display = 'none';
            

            // SAVE TO LOCAL STORAGE 
            savedChecks = document.querySelector('.saved-list-item').innerHTML;
            localStorage.setItem('checkedItems'+ new Date().getTime(), savedChecks);

        } 
    });
};


Even though this adjustment resolved the undefined property error, I remain puzzled about why the previous method failed to read the property accurately.

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

Is it possible to send data to the server in node.js before the page is loaded?

Once a user has logged in, their data is stored on the client side. There are certain pages that can be viewed without requiring a user to log in... For instance, I have created a route on node.js which generates a profile page based on a URL parameter. ...

I'm running into a "timeout" issue with socket.io and a self-signed SSL connection. Can anyone help me troubleshoot this?

After setting up a nodejs server with HTTPS, everything seems to be working fine when sending GET requests. However, I encountered an error message 'WebSocket was closed before the connection was established' when trying to connect another nodejs ...

What could be causing my jQuery to not retrieve the value of the <select> element?

Here's a snippet from my index.html file: <body> <select id="car"> <option value="TOYOTA">TOYOTA</option> <option value="BMW">BMW</option> </select> <input type=button id="get_btn" valu ...

Implementing universal design in Next.js 14

I'm encountering a problem while trying to use the style jsx global property in the latest version of Next.js. Previously, you would include it in the _app.js file, but since that file no longer exists, I assumed it should be added to the layout.tsx f ...

troubles with variables in AngularJS Formly templates

Having trouble displaying model or other variables in my template? Check out this link for reference: http://jsbin.com/wofulinufo/edit?html,js,output. Question: What is the solution for displaying variables from controller? Even when I try using {{model} ...

Tips for retaining form inputs without the need for a submit event when the page is reloaded or refreshed

I have a form on a page with multiple text inputs In addition to the form, I have implemented Zend pagination to allow users to select results. However, when using Zend paginate, the user's form inputs are lost because it is not submitted. Since th ...

Show JSON data as choices in a dropdown menu

On my webpage, I want to display a dropdown list populated with objects from a JSON file using JavaScript. Here is the structure of my HTML and JSON: HTML <html> <body> <select id="myid">MyList</select> <script src="m ...

Angular 6 is throwing an error stating that the element 'app-action-button' is not recognized

I'm facing an issue while trying to incorporate a component that is shared between modules. Unfortunately, all my attempts have resulted in the same error. Despite searching for solutions in similar questions, I have been unable to resolve this error ...

Passing the Angular $scope property into a function as an argument results in it being overwritten

I'm facing a peculiar issue that I can't quite wrap my head around. In my Angular 1.4 project, I have a variable called $scope.videoModel on the scope object, which serves as a model for capturing form data. When the form is submitted, the model ...

Unable to get i18next functioning in my Node.js Express backend

I'm currently facing difficulties in implementing localization for my nodeJS backend. Within my Angular frontend, I have a language-setting interceptor that successfully sets the language in the request header. You can refer to the image below which ...

Data-api configuration for bootgrid ajax

According to the BootGrid documentation, in order to set the HTTP method to GET or enable AJAX, one must use the method and ajax attributes in JavaScript. However, the Data-API example demonstrates the use of data-url and data-ajax, leading me to conclude ...

Utilizing JSON in a d3.js application within a Rails environment

I have been exploring the gem gon in order to generate JSON data from my Rails database. I have successfully managed to display this data in an alert, but now I am looking to visualize it using d3.js. Within my database named "users" with columns (name:st ...

Navigate to the appropriate Angular route using HTML5 mode in Rails

After removing the '#' symbol in angular by using html5Mode, everything seemed to work fine. However, upon refreshing the page, it started looking for the template in Rails instead of Angular, resulting in a "template not found" error. Angular R ...

What precautions can I take to safely and securely extend event handling?

I am currently developing a small JavaScript library that includes components requiring "messages" based on specific page events, which allow users to define response functions. I need to access general events like onkeydown and let users determine how eac ...

Passing a selected option in a select box to another website is achievable using JavaScript

I'm still learning JavaScript and I would like to have a user be directed to another page when they select an option from a dropdown menu. Any suggestions on how to accomplish this? ...

What is the best way to display label information on a Google line chart?

line graph column graph My graph continuously calls the Controller to fetch recent data from the Database. There are two lines on the graph, and I would like to display the names of each line (column) such as red=counts of something // brown=counts of so ...

What is the reason behind receiving the error "PHP Warning: Trying to access property "nodeType" on null" when using this PHP AJAX search function?

I am working on developing a real-time search feature inspired by an example from w3schools, which can be found at this link: https://www.w3schools.com/php/php_ajax_livesearch.asp. My task involves searching through an xml file containing 1000 different it ...

Encountered an error when attempting to access property 'connect' of an undefined value

I encountered an issue with pg.connect not being defined in the Handler module. My goal is to set up a table using postgres in fastify. In my routes handling folder, I manage the routes and send API requests. The error occurs when I navigate to http://loc ...

Understanding the application of JSON data can be simplified by following these

I am looking to manipulate dates by either adding or subtracting them, but I am unsure of how to extract the dates from the other data present. var fetch = require('node-fetch'); fetch('https://api.nasa.gov/planetary/earth/assets?lon=100.7 ...

Discovering the initial element in an array that meets a condition by employing an asynchronous function

I'm facing a rather peculiar issue. I need to locate the first element in an array that meets a certain condition, but the find function must be labelled as async because a promise is required for the search. Just to clarify, the code provided below ...