What is the process of updating values in an object that is part of an array?

I am currently facing an issue where I am attempting to implement an edit function to replace text and dates. While I have managed to successfully update the text using the DOM, the edited values revert back to their original form upon page refresh. I suspect this is happening because the object's values in the array are not being correctly retained after editing.

To tackle this problem, I believe utilizing a map function could help create a new array and display the updated array on the DOM.

Please take a look at the code snippet below:

let Editedmodal = document.querySelector("#edit-modal");
let editBtn = document.querySelector(".edit");

// Edit Task Function
function editTask(id) {
  let taskIndex = taskArray.findIndex((task) => task.id === id);
  let taskElement = document.querySelector(`.task-to-do[data-id="${id}"]`);

  // Accessing Edit Modal Element
  let Editedmodal = document.querySelector("#edit-modal");

  // Displaying Existing Task Details in Edit Form
  EditedInputTask.value = taskArray[taskIndex].task;
  EditedInputDate.value = taskArray[taskIndex].date;

  Editedmodal.style.display = "grid";

  // Submitting Edited Task
  EditedsubmitForm.addEventListener("click", (e) => {

    e.preventDefault();

    if (!EditedInputTask.value) {
      // Form Validation for Task Input
      EditedInputNoTask.style.display = "block";
      EditedInputTask.style.marginTop = "-1em";
      timeout = setTimeout(() => {
        EditedInputNoTask.style.display = "none";
        EditedInputTask.style.marginTop = "0";
      }, 3000);
    }

    if (!EditedInputDate.value) {
      // Form Validation for Date Input
      EditedInputNoDate.style.display = "block";
      EditedInputDate.style.marginTop = "-1em";
      
      // Timeout for Error Message
      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;

  });

}

// Storing Task Array Locally
function storeTaskArrayLocally() {
  localStorage.setItem("taskLocalstorage", JSON.stringify(taskArray));
}

// Initializing Task Array from Local Storage
function initializeTaskAraryFromLocalStoraege() {
  const storedTask = localStorage.getItem("taskLocalstorage");

  if (storedTask) {
    taskArray = JSON.parse(storedTask);
    renderTask();
  }
}

Answer №1

After making changes to a task in the task array, it is important to update and store the array in localStorage:

  // modify the task information in the array
  taskArray[taskIndex].task = EditedInputTask.value;
  taskArray[taskIndex].date = EditedInputDate.value;
  // save the updated task array in localStorage
  storeTaskArrayLocally();

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to implement the <b-pagination-nav> component in Bootstrap Vue?

I'm eager to begin using the featured in this guide. However, I'm struggling to figure out how to incorporate the tag into my website. The tutorial's instructions are unclear and as a newcomer, I'm finding it difficult to make it func ...

Ways to change the URL post saving a cookie with express?

I have written this code for user login in my Express router: if (password === realpassword) { res.cookie('thecookie', 'somethingliketoken'); res.redirect(302, '/somepages'); } else { res.status(403).end(); } The ...

Troubleshooting Angular MIME problems with Microsoft Edge

I'm encountering a problem with Angular where after running ng serve and deploying on localhost, the page loads without any issues. However, when I use ng build and deploy remotely, I encounter a MIME error. Failed to load module script: Expected a ...

Sending a XML file from a Vue application to an ASP.NET Core backend using axios

I'm encountering difficulties when trying to upload an xml file using axios to my asp .net server. Below is the code snippet I am using on the vue side to retrieve and upload the xml file: uploadXmlFile(file: any) { const rawFile = new XMLHttpRequ ...

What are the best practices for utilizing intro.js effectively on mobile devices?

Description When using introjs on mobile devices with a screen width of less than 600px, the tooltip ends up covering the element. When I hold the device horizontally, the tooltip adjusts its position accordingly. I attempted to apply custom CSS to the too ...

When using Expressjs MVC, encountering difficulties in retrieving data from mongoose in the listAll() function within the router

I'm currently working on implementing MVC-like architecture in Express.js for a very specific scenario. I suspect there may be an issue with promises, but I'm struggling to debug the problem effectively. Here's how the architecture is set u ...

Oops! There seems to be a mistake - the provider setPageProvider is not recognized

Struggling to implement pagination on my page using the AngularJS framework. Encountering the error Error: [$injector:unpr] Unknown provider: setPageProvider <- setPage. Despite rearranging the code, the issue persists. Attempted following a tutorial fr ...

When attempting to retrieve the data from a JSON file using an XMLHttpRequest, the result that is returned is [object object]

I am currently studying JSON and found a helpful guide on w3schools. Here is the code provided in the guide: https://www.w3schools.com/js/tryit.asp?filename=tryjson_ajax The guide also includes a sample JSON file: https://www.w3schools.com/js/json_demo.t ...

jQuery Dialog interface endlessly scrolls to the top

While debugging code for a project, I came across the use of jquery UI Dialog for popups. However, there seems to be an issue where the page keeps scrolling to the top while the dialog remains stationary wherever it was opened. Below is the code snippet in ...

What is the best way to reset the size of an element in webkit back to its original dimensions?

I am having an issue with an element that changes to display absolute and covers its parent element on focus via javascript. However, when it goes back to its default state on blur, it does not return to its original position. This problem seems to only o ...

The functionality of the Vue.js single file component is not performing as anticipated

Recently, I've been experimenting with Vue and Vue CLI. I came across this amazing vue-tabs-component that I would like to try out. Here is a snippet of my code from App.vue: <template> <div> <tabs> <tab name="Fir ...

Prevent the propagation of a particular CSS class's inheritance

I need to make modifications to an existing HTML5 app that features two unique themes. Here's an example of the current structure: <body class="theme1 theme2"> <div id="div1">I'm satisfied with both themes</div> <di ...

What are the solutions for resolving the TypeError when undefined is not an object error?

I'm currently working on a project where I need to fetch data from a JSON file using XMLHttpRequest and then store it in an array. However, I keep getting errors when attempting to do so. Take a look at this code snippet that seems to be causing the ...

Finding the Nearest Value in an Array

My code involves a changing total number that I need to match with the closest value in an array of numbers, returning the index of the matching person, which should be Mia Vobos. I am attempting to find two people whose scores add up to the same total or ...

The webpage becomes unresponsive and gets stuck when sending a stream of requests to the web server via ajax

I am currently working on creating a signal on the webpage that displays either a green or red color based on values retrieved from a database. However, when I send a request after 10 seconds, the page appears to freeze and becomes unresponsive. I am strug ...

What is the most efficient way to cycle through HTML image elements and display a unique random image for each one?

I'm currently working on coding a simple game that involves guessing the Hearthstone card based on its flavor text. I plan to add a button later to progress in the game, but I haven't implemented that yet. To start, I created 4 image elements an ...

There was an error in locating the JavaScript file within the Node.js Express Handlebars application

My website is not displaying the .js file, css file, or image from the public folder. Here are the errors showing up in the console: GET http://localhost:8080/assets/images/burger.jpg 404 (Not Found) GET http://localhost:8080/burgers.js net::ERR_ABORTED ...

Uploading files to AWS-S3 using Angular $http PUT method: A step-by-step guide

When attempting to upload a file to AWS-S3 using $http.put(url, file) in my Angular application, I encounter an issue. The HTTP-403 Forbidden error message indicates that the signature calculated by S3 differs from the one I provided. However, if I use c ...

Unable to interact with options in a dropdown menu while utilizing selenium

As a newcomer to the world of web scraping with Python using Selenium, I am trying to extract information on tennis players from the website "https://www.itftennis.com/en/players/". The challenge I am facing is related to navigating a drop-down list of res ...

When the margin-left changes, SVG begins to flicker and shake in a marquee effect

I've been experimenting with a marquee effect using vanilla JS. The effect is working, but I'm encountering some shaking issues with SVG and images as they move. <div class="marquee"> <h1>Nepal <svg version="1.1&qu ...