Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

109
Visualizações
Why local storage deletes data with toggled checkboxes?

I'm trying to make a to-do list. I'm in the middle of a process and get the following problem:

  1. I render a todo from input to a page - works fine.
  2. I save todos in local storage - works fine.
  3. I load todos from local storage - works fine, BUT when I tick a checkbox on a todo and refresh the page local storage deletes that particular todo. Can't figure out what's going on

HTML:

<body>
    
<ul id="list">
    
</ul>

<form action="submit" id="task-form">
    <input type="text" placeholder="Type your task here and click 'Add a Task'" id="task-input">
    <button type="submit" id="add-button" > Add a Task </button>
</form>

<template id="template">
    <li class="list-item" data-todo-id="">
        <label class="list-item-label">
           <input type="checkbox" id="checkbox">
           <span list-item-text> Task text is here </span>
        </label>
           <button type="button"> Delete </button>
     </li>
</template>

</body>

JS:

let button = document.querySelector('#add-button')
let todoInput = document.querySelector('#task-input')
let template = document.querySelector('#template')
let list = document.querySelector('#list')
let LOCAL_STORAGE_PREFIX = 'TO-DO LIST APP'
let LOCAL_STORAGE_KEY = `${LOCAL_STORAGE_PREFIX}-todos`
let todos = [];
let savedTodos = loadTodo();
savedTodos.forEach(renderTodo)

button.addEventListener('click', e =>{
    e.preventDefault();

    let date = new Date;

    let todo = {
        name : todoInput.value,
        complete : false,
        id : date.valueOf() }

    todos.push(todo)
    saveTodo();
    renderTodo(todo)

    console.log(todo)
    todoInput.value = ''
})

function renderTodo(todoName){
    let templateClone = template.content.cloneNode(true)
    let todoText = templateClone.querySelector('[list-item-text]')
    todoText.innerText = todoName.name
    list.appendChild(templateClone)
}

function saveTodo(){
    localStorage.setItem(LOCAL_STORAGE_KEY,JSON.stringify(todos)) 
}

function loadTodo(){
   return JSON.parse(localStorage.getItem(LOCAL_STORAGE_KEY)) || [] 
}
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

The checkbox doesn't have any event handlers attached, so checking/unchecking it will have no effect on the todos. However, you have a bug in your code, which will lead to all your previously saved todos being deleted if you add a new one. The checkbox thing, I believe was a co-incidence.

let todos = [];
let savedTodos = loadTodo();

Here two different arrays are being created, savedTodos contains the todo lists parsed from local storage. And an empty array called todos. The list of todos in savedTodos also gets added to dom on next line.

So far so good..

...
    todos.push(todo)
    saveTodo();
    renderTodo(todo)
...

However, in your addTodo function (add button event handler), when you add a new todo it is added to the (currently empty) todos array, and then is also written back to the local-storage. At this point, the existing todos will show in DOM, but have been deleted from local-storage. When you refresh the page, only the Todos added in the last session will show.

To fix this, I's recommend merging the todos and savedTodos array, and having only one of those.

...
let allTodos = loadTodo();
allTodos.forEach(renderTodo)

// in addTodo function (add button event handler)
   ...
   allTodos.push(todo);
   ...

// in saveTodo function 
   localStorage.setItem(LOCAL_STORAGE_KEY,JSON.stringify(allTodos));
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda