Deleted tasks are back in action after restoration

After adding 3 tasks like "Task1", "Task2", and "Task3", I accidentally removed one of them by pushing the recycle bin. To my surprise, when I added a new task "Task4", the previously removed task was restored as well. How can I fix this issue? Any explanations would be greatly appreciated.

'use strict';

const headerInput = document.querySelector('.header-input');
const todoControl = document.querySelector('.todo-control');
const todoList = document.querySelector('.todo-list');
const todoCompleted = document.querySelector('.todo-completed');

const todoData = [];

const render = function() {
    todoList.textContent = '';
    todoCompleted.textContent = '';

    todoData.forEach(function(item){
        const li = document.createElement('li');
        li.classList.add('todo-item');
        li.innerHTML = '<span class="text-todo">' + item.value + '</span>' + 
                        '<div class="todo-buttons">' +
                            '<button class="todo-remove"></button>' +
                            '<button class="todo-complete"></button>' +
                        '</div>';

        if(item.completed){
            todoCompleted.append(li);
        } else {
            todoList.append(li);
        }

        const btnTodoCompleted = li.querySelector('.todo-complete');

        btnTodoCompleted.addEventListener('click', function(){
            item.completed = !item.completed;
            render();
        })

        const btnRemove = li.querySelector('.todo-remove');

        btnRemove.addEventListener('click', function(){
            li.remove();
        });
    });

};


todoControl.addEventListener('submit', function(event){
    event.preventDefault();

    const newTodo = {
        value: headerInput.value,
        completed: false
    };

    todoData.push(newTodo)

    render();
});

render();

Answer №1

Every time a new task is created, it is added to the array:

todoData.push(newTodo)

However, when a task is deleted, the array remains unaltered. Instead, the <li> element is simply removed from the page:

li.remove();

As a result, the next time render() is called, the list will be re-rendered from the array which still contains the "deleted" record.

Instead of removing the <li> element, it is preferable to delete the record from the array and then call render() again:

btnRemove.addEventListener('click', function(){
    // Create a filtered version of the array
    todoData = todoData.filter(function (i) {
        // Only keep records that do not match the current one
        return item.value !== i.value;
    });
    // Re-render the list
    render();
});

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 data from a hashmap in a React component

Struggling with extracting data from a hashmap retrieved from an API for my React application. Here's a snippet of the data: [ [ "d243dc7-6fe8-151b-4ca8-1be528f2b36", "[\"Jonny\",70]" ], ...

The functionality of a switch statement relies on the presence of a React-Router

Is there a way to dynamically change the text in a paragraph based on which Route is currently enabled? I tried using a switch statement, but I'm unsure of how to implement it. Any suggestions or ideas? import React from 'react'; import &ap ...

Even with the text field populated and clearly existing, Firefox is still throwing a null error when trying to retrieve it using

Hey there! I'm currently working on a sample HTML page and I'm facing an issue with retrieving data from a text field. No matter what I try, I keep encountering the following error: TypeError: document.getElementById(...) is null Let me share t ...

having trouble accessing a JavaScript array in AngularJS

Hey there, I'm currently working on a web application using AngularJS and I'm facing an issue with querying arrays. Check out the code snippet below: var angulararray = []; bindleaselistings.bindleaselistingsmethod().then(function(response) { ...

Nodejs - how to achieve interoperability between mjs and js files through importing and requiring?

I'm fairly new to JavaScript and Node.js. Based on my research, it seems that ES6 import is not compatible with Node.js, so I've resorted to using experiment mode by renaming my file to .mjs. This workaround generally works, except when the .mjs ...

javascript regex for finding exact string match

Looking for a solution with JavaScript regex: /\[DEF\]([^\[\]]+)\[\/DEF\]/g Using the following string: [DEF]sdgsdggsFfg sdgsdg[/DEF] I need to ensure that no additional [/DEF] tags appear in the middle. After tweaki ...

What steps do I need to take in order to show the present value using a range input?

Hey there! I'm working on a code in HTML that includes an input of type range. Here's what it looks like: This is my input: <input type="range" min="1" max="100" value="50" class="slider" id="myRange"> Unfortunately, I'm unable to s ...

Is it possible to simultaneously execute an animate and a fade out effect?

Is there a way to simultaneously move "app1" to the left and fade it out? Currently, the functions are executing one after the other. I want them to occur simultaneously, without the left movement happening before the fade out. Thank you! <!DOCTYPE h ...

Explain the purpose of the describe() function in Mocha testing framework

Exploring Mocha has been a goal of mine and I recently came across this example in the documentation: var assert = require("assert") describe('Array', function(){ describe('#indexOf()', function(){ it('should return -1 when ...

What is the best way to retrieve the most recent CMS posts information within a Gatsby-constructed project?

I created a static website using Gatsby and everything was working well. However, I encountered an issue when updating the titles and content of posts in Contentful CMS - the changes were not reflected when I refreshed the website. How can I ensure that ...

Ways to expand component style using styled-components

I've created a simple ElipseDetail component that is displayed in the image below: https://i.sstatic.net/Kij7i.png <ElipseDetail text="1.07" /> Initially, everything works perfectly when using this component. Now, I'm intereste ...

Issue with printing error messages for JavaScript form validation

I have implemented the following code for a form to handle validation and display errors below the fields when they occur: <!DOCTYPE html> <html> <head> <style type="text/css"> .errorcss { background-color: yellow; color:re ...

What is the significance of "('_' + element + '_')" in coding?

function enlarge(element) { var target = document.getElementById(element); var currentHeight = target.offsetHeight; var scrollHeight = target.scrollHeight; var loopTimeout = setTimeout('enlarge(\'' + element + '&bso ...

Generate a new nested div if there is already a different child present at the specified coordinates (x, y)

My goal is to add a textarea to a sidebar on the right whenever a click is made on the page. The current code I have is as follows: $('#page_to_be_clicked').click(function(e){ var offset = $(this).offset(); var comment_box_y_coord = e.pa ...

Issue with Jquery checkbox calculator constantly displaying Not a Number (NaN)

I'm facing an issue with jQuery. The Custom Wpform Checkbox Field is returning NaN. HTML <div class="wpforms-payment-total"> $ 85 </div> <input type="checkbox" name="myBox2" size="1 ...

Refresh the three.js Raycaster when the window size changes

Currently, I am implementing a ray caster to choose objects within my three.js scene. The specific objects I am working with are box geometries shaped like flooring. After a successful selection of an object, I encountered an issue where resizing the wind ...

What is the best way to input an argument into my Javascript code using the command line?

Whenever I run my JavaScript file called "login.js" from the command line using "node login.js", I find it necessary to manually edit the URL inside the file if I want to change it. It would be more convenient for me if I could pass the URL as a command l ...

When attempting to send data from Ajax to PHP as JSON, an error occurs and the data transmission fails

When attempting to send data as JSON, an error response is received stating: SyntaxError: Unexpected token < in JSON at position 0. If the data is sent as text, it successfully reaches PHP, but PHP does not respond accordingly. AJAX/JavaScript using J ...

Is Javascript Profiling a feature available in Firebug Lite?

Exploring the world of JavaScript profiles, I decided to step away from the usual Chrome Developer tools. Can Firebug Lite for Google Chrome provide Javascript Profiling functionality? ...

What is the best way to save the raw text or event-stream data from a JavaScript get request when the server is continuously loading?

Currently, I'm attempting to fetch some basic data from an API. Here is the URL for the request: The issue lies in the fact that the server appears to keep refreshing the page constantly. This endless loading occurs both when using a browser and with ...