You don't have access to this class

Keep learning! Join and start boosting your career

Aprovecha el precio especial y haz tu profesión a prueba de IA

Antes: $249

Currency
$209
Suscríbete

Termina en:

2 Días
14 Hrs
32 Min
35 Seg

Eliminar y editar tareas del almacenamiento local

23/27
Resources

How to store tasks in localStorage using JavaScript?

Efficient data management is crucial in any modern application. In this case, we will explore how to store and manage tasks in the browser's localStorage using JavaScript, allowing modifications to persist even when refreshing the page. Ready to learn how to maintain the state of your tasks using JavaScript? Let's take it step by step.

How to make sure tasks persist after refreshing the page?

We start by saving our tasks in the localStorage. This ensures that even when you refresh the page, the record of the tasks already created is maintained. You can check the stored status of the tasks using the browser:

  1. Accessing the localStorage: You can view the stored tasks by inspecting the localStorage through the developer console.

  2. Storage structure: Tasks are stored in an array under a specific key, such as tasks, for easy access.

  3. Visual Feedback: Although we can delete and edit tasks from the user interface, without updating the localStorage, these changes are not permanent. We need to address this update to maintain memory across page refreshes.

How to implement the localStorage update after editing or deleting tasks?

To make the changes permanent when updating, we need to implement functions that reflect these modifications in the localStorage. Here is how to do it:

LocalStorage update function.

The updateLocalStorage function is called each time a task is edited or deleted and requires no parameters as it acts on the current state of the tasks.

function updateLocalStorage() { const taskElements = document.querySelectorAll('#task-list li'); const tasksArray = Array.from(taskElements).map(el => el.firstChild.textContent); localStorage.setItem('tasks', JSON.stringify(tasksArray));}
  • Retrieve Updated Content: we use querySelectorAll to get all <li> items from the task container, converting them to an array for manipulation.

  • Mapping and Serialization: Next, we map these nodes to retrieve their text content, achieving an array of updated tasks.

  • Storage: Finally, the array is serialized to a JSON string, storing it in the localStorage under the tasks key.

Automation with Edit

Integrate the updateLocalStorage function within the task edit flow to ensure that every change is reflected in the localStorage.

function editTask(taskIndex, newContent) { // Assume the functionality exists to make the changes in the UI document.querySelectorAll('#task-list li')[taskIndex].firstChild.textContent = newContent; updateLocalStorage();}

Why is it important to convert NodeLists to arrays?

When working with a NodeList (the structure returned by querySelectorAll), converting it to an array is crucial to take advantage of array methods, such as map, that are not available in a NodeList.

  1. Manipulation Flexibility: Using Array.from allows to quickly convert a NodeList to an array, providing access to methods such as map, filter and reduce.

  2. Ease of Iteration and Mapping: Once in array format, iterating and mapping to transform data becomes simple and effective.

Final Considerations

Using localStorage correctly, along with NodeList conversion and manipulation, allows state to be managed persistently in web applications. This ensures that operations in the user interface, such as adding, editing and deleting tasks, are automatically reflected in the stored state, taking the user experience to a new level of reliability and consistency. Don't underestimate the importance of the key-value storage capability that localStorage offers - it's a valuable resource in modern web development!

Keep exploring and honing your programming skills! Each tweak and new integrated feature is another step towards building more robust and complete applications.

Contributions 4

Questions 1

Sort by:

Want to see more contributions, questions and answers from the community?

Con el console.log(tasks) del principio, incluso una vez ya hacemos Array.from(taskList.querySelectorAll('li')) \[pero antes del map], podemos ver en consola la gran diferencia que hay entre `innerHTML` e `innerText`. 👀 Esto es interesante porque unas veces necesitaremos recuperar toda la información HTML (\
Para tener en cuenta firstChild retorna el contenido del primer nodo ![](https://static.platzi.com/media/user_upload/image-46836c90-9595-4618-b610-2288c9672a4f.jpg)![]() En este caso seria solo el texto. ![]()![](https://static.platzi.com/media/user_upload/image-d5f77c92-58b2-44f0-9871-f9706e808e5e.jpg) Posterior en createTaskElement(), se le añade los iconos.![]()
Cuando elimino una tarea y refresco la página, no me la elimina, me vuelve a aparecer la tarea ¿Me perdí de algo o no lo explica? ```js // Clase 1 (20): Añadir tareas desde un formulario const taskForm = document.getElementById("task-form"); const taskList = document.getElementById("task-list"); loadTasks() taskForm.addEventListener("submit", (event) => { event.preventDefault(); const taskInput = document.getElementById("task-input"); const task = taskInput.value; console.log(task); if (task) { taskList.append(createTaskElement(task)); storeTaskInLocalStorage(task); taskInput.value = ""; } }); function createTaskElement(task) { const li = document.createElement("li"); li.textContent = task; li.append(createButton("❌", "delete-btn"), createButton("✏️", "edit-btn")); return li; } function createButton(text, className) { const btn = document.createElement("span"); btn.textContent = text; btn.className = className; return btn; } // Clase 2 (21): Eliminar y editar tareas del DOM taskList.addEventListener("click", (event) => { if (event.target.classList.contains("delete-btn")) { deleteTask(event.target.parentElement); } else if (event.target.classList.contains("edit-btn")) { editTask(event.target.parentElement); } }); function deleteTask(taskItem) { if (confirm("Estás seguro de borrar este elemento?")) { taskItem.remove() } } function editTask(taskItem) { const newTask = prompt("Edita la tarea:", taskItem.firstChild.textContent); if (newTask !== null) { taskItem.firstChild.textContent = newTask; updateLocalStorage() } } // Clase 3 (22): Almacenamiento y carga de datos en localStorage function storeTaskInLocalStorage(task) { const tasks = JSON.parse(localStorage.getItem("tasks") || "[]") tasks.push(task); localStorage.setItem("tasks", JSON.stringify(tasks)); } function loadTasks() { const tasks = JSON.parse(localStorage.getItem("tasks") || "[]"); tasks.forEach((task) => { taskList.appendChild(createTaskElement(task)); }); } // Clase 4 (23): Eliminar y editar tareas del almacenamiento local function updateLocalStorage() { const tasks = Array.from(taskList.querySelectorAll("li")).map( (li) => li.firstChild.textContent); localStorage.setItem("tasks", JSON.stringify(tasks)); } ```
Local storage diria que es la forma mas usada por principiantes para guardar "datos en la nube", obviamente no porque los guarda asi, si no que antes creia que para paginas donde se deberian guardar configuraciones, debia conectarme a un servidor y traer esa config, pero con localStorage eso es un peso menos de encima (por ahora)