Save todos in localStorage

删除回忆录丶 提交于 2021-02-19 03:42:09

问题


I've created a todo app, and I want to save the todo's in localStorage.

I was thinking to add the localStorage property like this:

addForm.addEventListener("submit", (e) => {
    e.preventDefault();
    let todo = addForm.add.value.trim();
    if (todo.length) {
        localStorage.setItem(todo);
        generateTemplate(todo);
        addForm.reset();
    }
}

But, it's not working.

So, my question is, in which part of the code is it best practice to add the property and in which part is it best to also add the getItem method?


Here is the whole code without the localStorage property:

const addForm = document.querySelector(".add");
const list = document.querySelector(".todos");
const search = document.querySelector(".search input");

// generate new toDo's
const generateTemplate = (todo) => {
  let html = ` <li class="list-group-item d-flex justify-content-between align-items-center">
    <span>${todo}</span><i class="far fa-trash-alt delete"></i>
  </li>`;
  list.innerHTML += html;
};

// submit the todo
addForm.addEventListener("submit", (e) => {
  e.preventDefault();
  let todo = addForm.add.value.trim();
  if (todo.length) {
    generateTemplate(todo);
    addForm.reset();
  }
});

// delete todo's

list.addEventListener("click", (e) => {
  if (e.target.classList.contains("delete")) {
    e.target.parentElement.remove();
  }
});

// filter the toDo's

const filterTodos = (term) => {
  Array.from(list.children)
    .filter((todo) => !todo.textContent.toLowerCase().includes(term))
    .forEach((todo) => todo.classList.add("filtered"));

  Array.from(list.children)
    .filter((todo) => todo.textContent.toLowerCase().includes(term))
    .forEach((todo) => todo.classList.remove("filtered"));
};

search.addEventListener("keyup", () => {
  const term = search.value.trim().toLowerCase();
  filterTodos(term);
});
body {
  background-color: #352f5b;
}

.container {
  max-width: 400px;
}

input[type="text"],
input[type="text"]:focus {
  color: #fff;
  border: none;
  background: rgba(0, 0, 0, 0.2);
  max-width: 400px;
}

.todos li {
  background: #423a6f;
}

.delete {
  cursor: pointer;
}

.filtered {
  display: none !important;
}
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>toDoList</title>
  <script src="https://kit.fontawesome.com/fa5117c01c.js" crossorigin="anonymous"></script>
  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" integrity="sha384-JcKb8q3iqJ61gNV9KGb8thSsNjpSL0n8PARn9HuZOnIxN0hoP+VmmDGMN5t9UJ0Z" crossorigin="anonymous" />
  <link rel="stylesheet" href="style.css">
</head>

<body>
  <div class="container">
    <header class="text-center text-light my-4">
      <h1 class="text-ligth mb.4">thingsToDo</h1>
      <form action="" class="search"><input type="text" class="form-control m-auto" name="search" placeholder="Search toDo's"></form>
    </header>
    <ul class="list-group todos mx-auto text-light"></ul>
    <form class="add text-center my-4">
      <label class="text-light">Add new toDo...</label>
      <input type="text" class="form-control m-auto" name="add">
    </form>
  </div>
  <script src="index.js"></script>
</body>

</html>

回答1:


Storages object (what you use with LocalStorage) allows to save Strings (DOMStrings to be specific), so if you want to save a javascript object, you should convert it to string first (eg. with JSON.stringify)

On your code, also, the syntax for setItem is incorrect. You need to specify a key that identifies the object

   localStorage.setItem('todo', todo);

Notice that this will only save a todo. Therefore, when you get todo's back you will need to do localStorage.getItem('todo') and this of course will only return the last todo that you have saved.

A solution for this might be to have a storage for your todos:

var todos = []

Everytime you create a new todo you add that todo to this object

todos.push(todo)

and saves it to localstorage

localStorage.setItem('todos', JSON.stringify(todos))

When you get back that list, you will need to parse the string back to get the actual object:

var todosString = localStorage.getItem('todos');
var todos = JSON.parse(todosString);

Take into account that this will only get your todos data into that var. Then you need to repopulate your dom. This can be done by reusing your generateTemplate function. Eg.

todos.forEach(todo => generateTemplate(todo));

I'd also recommend you to take a look at the MDN page for LocalStorage: https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage

And the Using the Web Storage API page for a full working example: https://developer.mozilla.org/en-US/docs/Web/API/Web_Storage_API/Using_the_Web_Storage_API



来源:https://stackoverflow.com/questions/63839805/save-todos-in-localstorage

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!