learn how to implement local storage for a to-do list application using JavaScript

How do I implement the storage property in this code snippet? The current code is not functioning correctly and resets after each page refresh.

Please review my code at the following link: https://jsfiddle.net/74qxgonh/

let values = [];

// Accessing Form Element (add text)
document.querySelector("form").addEventListener("submit", (e) => {
  e.preventDefault();

  // Creating an object with a unique id
  storageValue = {
    id: "num" + Math.floor(Math.random() * (1000, 9000)),
    text: e.target.elements.textInput.value,
  };

  // Adding the object to array for saving to localStorage
  values.push({ storageValue });
  localStorage.setItem("values", JSON.stringify(values));
  
  // Creating Tags dynamically
  let input = document.createElement("input");
  input.setAttribute("type", "checkbox");
  input.setAttribute("class", "chk-box");
  input.setAttribute("id", `${storageValue.id}`);

  let label = document.createElement("label");
  label.textContent = `${storageValue.text}`;
  label.setAttribute("for", `${storageValue.id}`);
  label.setAttribute("class", "chk-label");

  const btnDeleted = document.createElement("button");
  btnDeleted.setAttribute("class", "btn-delete");
  btnDeleted.textContent = "X";
  btnDeleted.addEventListener("click", () => {
    div.remove();
  });

  const div = document.createElement("div");
  div.setAttribute("class", "inputGroup");
  div.appendChild(input);
  div.appendChild(label);
  div.appendChild(btnDeleted);

  document.querySelector(".container-center").appendChild(div);

  e.target.elements.textInput.value = "";
});

Answer №1

One simple solution might be to modify the initial line of your code in order to retrieve the previously saved items from localStorage, rather than creating an empty array every time the application is loaded:

// original
let items = [];
// updated
let items;

try {
  items = JSON.parse(localStorage.getItem('items')) ?? [];
} catch {
  items = [];
}

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

Diving into Discord.JS - Is there a way to check if a specific message content exists within an array?

I'm currently working on developing a Discord user verification bot that generates a 2048-bit key upon joining a server. This key will be crucial for verifying your account in case it gets compromised or stolen, ensuring that the new account belongs t ...

Innovative sound system powered by React

I am working on implementing a music player feature on a website where users can select a song and have it play automatically. The challenge I am facing is with the play/pause button functionality. I have created all the necessary components, but there see ...

ways to undo modifications made to a value within an input field using jquery or javascript

$(document).ready(function () { //Highlight row when selected. $(function () { $('#Cases tr').click(function () { $('#Cases tr').removeClass('selectedRow'); $(this).addClass(&apos ...

Discovering the Value of TD when Clicked in MVC

I have been struggling to extract a value or string from a td in a table, but none of the clickevents I've used seem to work. Here is the structure of the table: <table id="tblMain"> <thead> <tr> ... </tr> ...

The curly braces in AngularJS are not resolving as expected, however, the ng-bind directive is functioning properly

I'm currently working on a Django application and utilizing AngularJS for my frontend. I have a straightforward piece of code that looks like this: <div class="vert-carousel" ng-controller="PrizeController"> <div class="gallery-cell" n ...

How can one extract dates from a range using mongoose?

Currently, I am working on a rental app project. One of the key functionalities I am trying to implement is the ability to determine the availability of cars between two specified dates, including those dates themselves. Within the database, I have two mai ...

Activate jQuery function upon clicking a bootstrap tab

When I click on a Bootstrap tab, I want to trigger an AJAX function. Here is the HTML code: <li><a href="#upotrebljeni" data-toggle="tab">Upotrebljeni resursi</a></li> The jQuery AJAX function looks like this: $('a #upotreb ...

Fetching data from a Django view using a JavaScript AJAX POST call

Utilizing Javascript for an asynchronous request to a Django View, I am able to successfully receive data from the POST request. However, I am encountering issues with returning a confirmation message that the process was successful. Despite expecting xhtt ...

Protractor: Unable to reach variables within closure set in the parent function

I have a code snippet in one of my JS files that looks like this: // test/lib/UserHelper.js 'use strict'; var Firebase = require('firebase'); exports.createUser = function (email, password) { browser.executeAsyncScript(function (do ...

What is the best way to create a command that updates the status in Discord using discord.js?

I'm currently working on a command for my Discord bot using discord.js. The purpose of this command is to change the bot's status whenever an admin of the server triggers it. I've attempted to create the command, but unfortunately, it's ...

Determine whether child components in React Native contain additional child elements

I'm facing an issue while trying to determine if the children (AssetExample2) of my parent (AssetExample) component have their own children. The goal is to use this logic for the splash screen of my app to hide it once the children have loaded. Howeve ...

Unlocking the state of a recurring component in ReactJS

Just started learning reactjs. Currently, I am working on accessing the state of a repeated react component. Below is a snippet of my code: {Object.keys(this.state.sharing).map((share)=>{ return(<Sharings /> ...

Get rid of the folder from the URL using an <a> tag

I have both an English and French version of my website located at: *website.com/fr/index.php *website.com/index.php Currently, I have a direct link to switch between the two versions: -website.com/fr/index.php -website.com/index.php. However, I ...

PHP scheduler alternative

I have a PHP script called updater.php that performs a task for 1-2 minutes. It is crucial for the script to complete its job. While I can schedule it with cron, I have come up with an alternative solution. The script should only run at specific times wh ...

Navigating with Node.js: Understanding how to showcase the response data within a list structure

I am brand new to working with node.js and I'm looking to display the data I receive as a response on my webpage. Currently, I can see the output in my console. Is there a way to show this data on my actual page? GET Request: app.get('/bestell_ ...

Exploring the syntax of Vue's data function

I encountered a syntax error while compiling my assets: Syntax Error: SyntaxError: C:\xampp\htdocs\dtcburger.com\resources\js\components\stripe\STRIPEform3.vue: Unexpected token, expected ";" (51:12) 49 | { ...

Could you guide me on how to utilize Sencha Touch for saving information in a JSON file?

I am in the process of creating a simple Sencha Touch application to become more comfortable with the platform. My goal is to have the store (currently set up as shown below) read and write data to/from a local JSON file. Additionally, I would like the sto ...

Loading Data into Array - Angular/Ionic

I am currently developing an App and encountering issues with pushing data into an array. It seems that there is a problem in my code. Would you mind taking a look? Error Message Thrown: ionic.bundle.js:25642 TypeError: Cannot read property 'title&ap ...

How to eliminate the ng-component tag from an Angular 8 table row template

I currently have a dynamic table component with 2 modes: Normal table - functioning properly Custom Row Template - encountering issues due to Angular adding the <ng-component> tag The logic within the TableComponent is not the main concern, it&apo ...

Adding and removing controls on Google Maps in real-time

Recently, I encountered an issue with my custom search bar overlapping some controls on my map. Despite adjusting the z-index of these controls, they continued to stay on top. To work around this problem, I thought about hiding the controls during the sear ...