I added 3 tasks, for example "Task1", "Task2", "Task3", then removed one of them. Pushing on recycle bin, the task will be removed, but when I add new task "Task4", removed task will be restored too.
How to do I fix it? Please add an explanation if possible?
'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();
When you create a new task, you add a record to the array:
todoData.push(newTodo)
But when you delete a task, you don't modify the array. You just delete the <li>
element from the page:
li.remove();
So the next time render()
is called, it will re-render the list from the array which still contains the "deleted" record.
Instead of deleting the <li>
element, delete the record from the array and re-invoke render()
:
btnRemove.addEventListener('click', function(){
// re-assign the array to a filtered version of itself
todoData = todoData.filter(function (i) {
// only return records which don't match the current record
return item.value !== i.value;
});
// re-render the list
render();
});