The problem I am facing is that I am trying to replace the text and date with an edit function. I got it working to a point where it is replacing the text via the DOM, but when the page refreshes the edited version resets to its old values. I think I know why, it is because the values within the object that is in the array need to stay changed and it is not, which I do not think I am doing correctly.
I think maybe using a map, which could create a new array and render the updated array on the DOM.
Please review the code below:
let Editedmodal = document.querySelector("#edit-modal");
let editBtn = document.querySelector(".edit");
function editTask(id) {
let taskIndex = taskArray.findIndex((task) => task.id === id);
let taskElement = document.querySelector(`.task-to-do[data-id="${id}"]`);
let Editedmodal = document.querySelector("#edit-modal");
EditedInputTask.value = taskArray[taskIndex].task;
EditedInputDate.value = taskArray[taskIndex].date;
Editedmodal.style.display = "grid";
/*Submit Edited task Form*/
EditedsubmitForm.addEventListener("click", (e) => {
e.preventDefault();
/*Form Validaion*/
if (!EditedInputTask.value) {
EditedInputNoTask.style.display = "block";
EditedInputTask.style.marginTop = "-1em";
timeout = setTimeout(() => {
EditedInputNoTask.style.display = "none";
EditedInputTask.style.marginTop = "0";
}, 3000);
}
if (!EditedInputDate.value) {
EditedInputNoDate.style.display = "block";
EditedInputDate.style.marginTop = "-1em";
timeout = setTimeout(() => {
EditedInputNoDate.style.display = "none";
EditedInputDate.style.marginTop = "0";
}, 3000);
} else {
Editedmodal.style.display = "none";
EditedInputTask.value = "";
EditedInputDate.value = "";
taskArray[taskIndex].task = taskObjEdited;
taskArray[taskObjEdited.task] = DateStore;
}
taskArray[taskIndex].task = EditedInputTask.value;
taskArray[taskIndex].date = EditedInputDate.value;
taskElement.querySelector("#list-item-date").textContent = `Due: ${taskArray[taskIndex].date}`;
taskElement.querySelector("#list-item-task").textContent = taskArray[taskIndex].task;
});
function storeTaskArrayLocally() {
localStorage.setItem("taskLocalstorage", JSON.stringify(taskArray));
}
function initializeTaskAraryFromLocalStoraege() {
const storedTask = localStorage.getItem("taskLocalstorage");
if (storedTask) {
taskArray = JSON.parse(storedTask);
renderTask();
}
}
When you change a task in the task array you need to store the array in localStorage again:
// change the task in the array
taskArray[taskIndex].task = EditedInputTask.value;
taskArray[taskIndex].date = EditedInputDate.value;
// store the task array in localStorage
storeTaskArrayLocally();