StephenW
StephenW

Reputation: 183

How to add local storage to updated/edited text?

I have managed to successfully add local storage to the addToDo function. So when a todo item is added the local storage is set and retrieved for each item(line 33 in codepen). However, I cannot figure out how to add the same local storage function to the updated item text. Note: To update item, user clicks off of item after typing in textarea.

If I add the addToLocalStorage function in the createTodoText function before itemText is returned, it does not work. If possible I also need to add local storage for the checkbox state and delete state as I am sure it is similar. This codepen is what I have tried.

const createTodoText = (todo) => {
    const itemText = document.createElement('TEXTAREA');
    itemText.setAttribute('id', 'display-text');
    itemText.classList.add('todoText');
    itemText.addEventListener('input', function () {
        updateHeight(this);
    });
    itemText.value = todo.name;
    //update todo item when user clicks away
    itemText.addEventListener('blur', (e) => {
        todo.name = e.currentTarget.value;
    });
    //addToLocalStorage(todos)
    return itemText;
};

const addToLocalStorage = (todos) => {
  localStorage.setItem('todos', JSON.stringify(todos));
  renderTodos(todos);
}

const getFromLocalStorage = () => {
  const reference = localStorage.getItem('todos');
  if (reference) {
    todos = JSON.parse(reference);
    renderTodos(todos);
  }
}

getFromLocalStorage();

Upvotes: 0

Views: 55

Answers (1)

nay
nay

Reputation: 1775

it is simple,just add addToLocalStorage function to the event listener callback function will work.
createTodoText does run when todo list rendering,you want update localstorage,you need do that after todo item updated,which is after blur

const createTodoText = (todo) => {
    const itemText = document.createElement('TEXTAREA');
    itemText.setAttribute('id', 'display-text');
    itemText.classList.add('todoText');
    itemText.addEventListener('input', function () {
        updateHeight(this);
    });
    itemText.value = todo.name;
    //update todo item when user clicks away
    itemText.addEventListener('blur', (e) => {
        todo.name = e.currentTarget.value;
        addToLocalStorage(todos);
    });
    return itemText;
};

and I have update the codepen.
if you have further question,leave a comment

Upvotes: 2

Related Questions