Home > Software engineering >  How to change a local storage object value
How to change a local storage object value

Time:10-22

I am writing a todo list app and I have a problem when I press the edit button to change a task value, I want to change the value of the input task, change it in the object task "title" and save it in local storage.

const inputWriteTask = document.querySelector("input"),
    buttonAddTask = document.querySelector("button"),
    containerTasks = document.querySelector(".container-tasks");

let arrayOfTasks = [];

function buttonAddtasksToArray() {
    if (inputWriteTask.value != "") {
        addValueInput(inputWriteTask.value);
        inputWriteTask.value = "";
    };
};

buttonAddTask.addEventListener("click", buttonAddtasksToArray);

function addValueInput(text) {
    const task = {
        id: Date.now(),
        title: text,
    };

    arrayOfTasks.push(task);
    console.log(arrayOfTasks);
    createTasks(arrayOfTasks);
    addDataToLocaleStorage(arrayOfTasks)
};

function createTasks(arrayOfTasks) {
    containerTasks.innerHTML = "";
    arrayOfTasks.forEach(task => {
        let div = document.createElement("div");
        div.className = "task";
        containerTasks.appendChild(div)

        let inputText = document.createElement("input")
        inputText.type = "text"
        inputText.setAttribute("value", task.title)
        inputText.setAttribute("readonly", "")

        let editButton = document.createElement("button");
        editButton.className = "edit-btn";
        editButton.appendChild(document.createTextNode("edit"))
        div.append(inputText, editButton)

        editButton.onclick = () => {
            inputText.removeAttribute("readonly");
            inputText.focus();
        };
    });
};

function addDataToLocaleStorage(arrayOfTasks) {
    window.localStorage.setItem("data-task", JSON.stringify(arrayOfTasks));
};

if (localStorage.getItem("data-task")) {
    arrayOfTasks = JSON.parse(localStorage["data-task"])
    createTasks(arrayOfTasks)
}
<!DOCTYPE html>
<html lang="en">

    <head>
        <meta charset="UTF-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Document</title>
        <script defer src="main.js"></script>
    </head>

    <body>
        <style>
            .container-tasks {
                display: grid;
                gap: 1em;
                margin-top: 1em;
            }

            .task {
                background-color: #ddd;
                padding: 1em;
                display: flex;
                justify-content: space-between;
            }

            .task input {
                border: none;
                outline: none;
                background-color: transparent;
            }
        </style>
        <input type="text">
        <button>add task</button>
        <div >
        </div>
    </body>

</html>

CodePudding user response:

To edit a specific index of that array that is saved in local storage, you have to keep track of the index of each entries. You can use a data- attribute for this.

function createTasks(arrayOfTasks) {
  containerTasks.innerHTML = "";
  arrayOfTasks.forEach((task, index) => {
    let div = document.createElement("div");
    div.className = "task";
    div.setAttribute("data-taskindex", index);
    containerTasks.appendChild(div);

...

And on input blur, pass that index value to the addValueInput.

function addValueInput(text, index = -1) {
  const task = {
    id: Date.now(),
    title: text
  };

  if (index === -1) {
    arrayOfTasks.push(task);
  } else {
    arrayOfTasks[index] = task;
    // OR! If you whish to keep the original id (a date)
    // arrayOfTasks[index].title = text;
  }
  console.log(arrayOfTasks);
  createTasks(arrayOfTasks);
  addDataToLocaleStorage(arrayOfTasks);
}

So if there was no passed index... It pushes a new task to the array. And if there is one, it overwrites that specific index instead.

Here is the event handler (located in your createTasks function):

inputText.addEventListener("blur", (event) => {
  let index = event.target.closest("div").dataset.taskindex;
  console.log(`The task at index # ${index} was modified.`);
  addValueInput(event.target.value, index);
});

Since localStorage is not allowed here, have a look at this CodePen

  • Related