0

I am tasked with creating a to do list form . The User should be able to input their 'todos' and then be displayed those todos. The user has the option to remove and cross out each todo. When the user refreshes the page, the local storage should display the todos that the user inputed.

I am able to return all the inputs that are saved in the local storage at first try. However, once I cleared the console I realized my inputs are no longer being saved to the local storage. Every time I insert an input- the input does not save to local storage. enter image description here.

attached is the display browser.

Sorry for the sloppy code. I have just started my code learning. Any help would be appreciated !

const form = document.querySelector("form");
// const li = document.querySelector("li");
const ul = document.querySelector("#todolist");
const input = document.querySelector("#TO-DO");
let todoArray;


if (localStorage.todos) {
  todoArray = JSON.parse(localStorage.todos);
} else {
  todoArray = [];
}

for (let todo of todoArray) {
  addTodo(todo);
}

function addTodo(userInput) {
  const newToDo = document.createElement("li");

  newToDo.innerText = userInput;
  ul.appendChild(newToDo);
  newToDo.addEventListener("click", function (e) {
    if (e.target.tagName === "LI") {
      newToDo.classList.toggle("completed");
    }
  });
  const removeBtn = document.createElement("button");
  removeBtn.innerText = "REMOVE";
  removeBtn.addEventListener("click", function () {
    removeBtn.parentElement.remove();
    removeFromLocalStorage(userInput);
  });
  newToDo.prepend(removeBtn);
}

const userInput = input.value;

ul.addEventListener("click", function (e) {
  
  if (e.target.tagName === "BUTTON") {
    e.target.parentElement.remove();
  } else if (e.target.tagName === "LI") {
  }
});

form.addEventListener("submit", function submit(e) {
  e.preventDefault();

  const newToDo = document.createElement("li");
  const removeBtn = document.createElement("button");
  const userInput = input.value;
  

  removeBtn.innerText = "REMOVE";
  removeBtn.addEventListener("click", function () {
    removeBtn.parentElement.remove();
  });

  newToDo.innerText = userInput;
  input.value =
    ""; /* resetting the input value to be empty after we retieve value */
  ul.append(newToDo);
  newToDo.appendChild(removeBtn);
  newToDo.addEventListener("click", function (e) {
    if (e.target.tagName === "LI") {
      //   console.log("YOU CLICKed lI");
      newToDo.classList.toggle("completed");
    }
  });
});

function addToLocalStorage(userInput) {
  todoArray.push(userInput);
  localStorage.setItem("todos", JSON.stringify(todoArray));
}

function removeFromLocalStorage(userInput) {
  for (let i = 0; i < todoArray.length; i++) {
    if (todoArray[i] === userInput) {
      todoArray.splice(i, 1);
      break;
    }
  }
  localStorage.setItem("todos", JSON.stringify(todoArray));
}

  • Does this answer your question? [How to store objects in HTML5 localStorage/sessionStorage](https://stackoverflow.com/questions/2010892/how-to-store-objects-in-html5-localstorage-sessionstorage) – tevemadar Jan 04 '23 at 17:05
  • @tevemadar: Why? There is already JSON.stringify and JSON.parse in the code. – CherryDT Jan 04 '23 at 17:09
  • I don't see your code reading from `localStorage` anywhere. It would be `localStorage.getItem("todos")`. Ok, now I see, just the attempt with `localStorage.todos` does not exist. – tevemadar Jan 04 '23 at 17:13
  • @tevemadar These two methods of access are equivalent, both work the same (except for keys clashing with other property names of course, but that's not the case for `todos`). You can try it yourself or read the [spec](https://html.spec.whatwg.org/multipage/webstorage.html#the-storage-interface). It's also explained [on MDN](https://developer.mozilla.org/en-US/docs/Web/API/Web_Storage_API/Using_the_Web_Storage_API#basic_concepts). – CherryDT Jan 04 '23 at 17:25

2 Answers2

1

It looks like you are not calling your addToLocalStorage(userInput) function anywhere, so that is probably why they are not being written to local storage.

Try adding addToLocalStorage(userInput) to the end of your addTodo function.

anon
  • 816
  • 5
  • 17
-1

Add string to local storage

const localString = 'abc'

localStorage.setItem('str', localString)

Get string from local storage

// gives undefined if item doesn't exist on localStorage

localStorage.getItem('str') 

Add array to local storage

const localArray = ['one','two','three'] 

/* we will store this as storedItems. For this, we will have 
to first convert the array into string using JSON.stringify because we can't 
store array directly in local storage. We can only store strings in it*/

localStorage.setItem('storedItems', JSON.stringify(localArray))

Get array from local storage

// if storedItems doesn't exist then we will return empty array

JSON.parse(localStorage.getItem('storedItems') || '[]') 
Sandeep Amarnath
  • 5,463
  • 3
  • 33
  • 43
  • 1
    How is this helpful? The OP is already doing that. – CherryDT Jan 04 '23 at 17:09
  • 1) an `if` loop does not exist, an `if` statement is a conditional statement and not a loop. 2) what they do _is_ correct and has the same effect as what you wrote. Try it! 3) if you see something that is wrong in particular then you should explain what that is and why, and not respond with something that looks like you are writing examples for a documentation without providing context of why it is relevant to the particular question. – CherryDT Jan 04 '23 at 17:14
  • Alright, if you think you are right then that's alright, never mind. I am just here to help by giving additional info. If you already know stuff, then that's good for you. – Sandeep Amarnath Jan 04 '23 at 17:15