StephenW
StephenW

Reputation: 183

How come the last item count is not filtering on delete?

I have a todo list with CRUD. I just implemented a task counter to show the number of tasks left to complete. The count increments/decrements with checking/unchecking items and decrements on deleting items. Except there is one problem. For some reason on the last item deleted, the count stays at 1 instead of going to 0. Full Codepen

Here is what I tried:

function renderTaskCount() {
    const incompleteTaskCount = todos.filter((item) => !item.completed).length;
    const taskString = incompleteTaskCount === 1 ? 'task' : 'tasks';
    listCountElement.innerText = `${incompleteTaskCount} ${taskString} remaining`;
    return incompleteTaskCount;
}

const renderTodos = () => {
    ul.innerHTML = '';
    todos.forEach((item) => {
        let li = document.createElement('LI');
        li.setAttribute('class', 'item');
        li.setAttribute('data-key', item.id);
        const itemText = createTodoText(item);
        const cb = buildCheckbox(item);
        const db = buildDeleteButton(item);
        li.append(cb);
        li.append(db);
        li.append(itemText);
        ul.append(li);
        //update height of textarea
        updateHeight(itemText);
        renderTaskCount();
    });
};

Upvotes: 0

Views: 67

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 371069

You have

const renderTodos = () => {
    ul.innerHTML = '';
    todos.forEach((item) => {
        let li = document.createElement('LI');
        li.setAttribute('class', 'item');
        li.setAttribute('data-key', item.id);
        const itemText = createTodoText(item);
        const cb = buildCheckbox(item);
        const db = buildDeleteButton(item);
        li.append(cb);
        li.append(db);
        li.append(itemText);
        ul.append(li);
        //update height of textarea
        updateHeight(itemText);
        renderTaskCount();
    });
};

where renderTaskCount updates the count - which is done at the end of each iteration. So if the todos array is empty, the count will never be updated. You need

const renderTodos = () => {
    ul.innerHTML = '';
    todos.forEach((item) => {
        // ...
    });
    renderTaskCount();
};

so that whether renderTaskCount executes whether or not the todos array is populated.

Upvotes: 1

Related Questions