Creating a simple to-do list, I noticed that upon refreshing and retrieving data from the local storage, instead of just displaying "wash dishes", it shows as {"TODO_ITEM:1":"wash dishes"}

I have created a basic todo list where I am facing an issue. When I add an item like "wash dishes" through the input, it displays correctly. However, upon refreshing the page and accessing the object in the array from local storage, I get back {"TODO_ITEM:1":"wash dishes"}. I believe there is a mistake in how I am accessing the data. I have tried various methods found online but none seem to work properly. This is one of my first coding projects, so any advice or suggestions would be greatly appreciated!

//Selecting elements
const list = document.querySelector('#todo-list');
const form = document.querySelector('#create-todo');
const input = document.querySelector('#new-todo');
let todoCount = 1;
let obj = {};
let todo = [];

// Listens for click events on list items and buttons
list.addEventListener('click', function(e) {
  if (e.target.tagName === 'LI') {
    e.target.classList.toggle('done');
  } else if (e.target.tagName === 'BUTTON') {
    e.target.parentElement.remove();
  }
})

// Handles form submission to create a new todo
form.addEventListener('submit', function(e) {
  // Prevent default form submission
  e.preventDefault();
  // Add todo item to local storage
  addToLocalStorage(todo)
  // Create new list item with button
  createLi()

  console.log(localStorage)
})

// Fetches data from local storage
function getFromLocalStorage() {
  const reference = localStorage.getItem('TODO_LIST')
  if (reference) {
    todo = JSON.parse(reference)
    renderTodo(todo)
  }
}

// Function to create a new list item
function createLi() {
  const newLi = document.createElement('li');
  const newBtn = document.createElement('button');

  newLi.innerText = input.value;
  list.append(newLi);

  newBtn.innerText = 'Remove';
  newLi.append(newBtn);
  input.value = '';
}

// Function to add item to local storage
function addToLocalStorage(todo) {
  let obj = {}

  let key = 'TODO_ITEM:' + todoCount
  console.log(obj)
  todoCount++
  obj[key] = input.value
  todo.push(obj)
  localStorage.setItem('TODO_LIST', JSON.stringify(todo))
}

// Function to keep todo list displayed after refresh
function renderTodo() {
  list.innerHTML = '';

  for (let i = 0; i < todo.length; i++) {
    console.log(todo[i])
    let indx = todo[i]
    const newLi = document.createElement('li');
    const newBtn = document.createElement('button');
    newLi.innerText = JSON.stringify(indx);
    list.append(newLi);
    console.log()
    newBtn.innerText = 'Remove';
    newLi.append(newBtn);
    console.log(indx)
  }
}

getFromLocalStorage();

Answer №1

Latest Update

The main issue lies in the way todos are stored in the localstorage as JavaScript objects with this format:

// { key: value }
{"TODO_ITEM:1": "Todo value"}

Therefore, when retrieving them later on, you must access the value within the object that contains the todo text:

function getFromLocalStorage() {
  // this retrieves a list of todos following the above structure
  const reference = localStorage.getItem('TODO_LIST');

  if (reference) {
    const todoItems = JSON.parse(reference);

    // iterate over the todos array to extract individual todos
    todoList = todoItems.map((item) => {
      // utilize Object.values to extract the 'Todo value' from the object {"TODO_ITEM:1": "Todo value"}
      const todoValue = Object.values(item)[0];
      return todoValue;
    });
    todo = todoList;
    renderTodo(todo);
  }
}

In your renderTodos function, avoid stringifying the value:

// Remove this
newLi.innerText = JSON.stringify(indx);

// add this
newLi.innerText = indx;

For further details on Object.keys(), check this resource, and for array.map(), refer to this link.

Improved Version

To simplify the process, consider storing just a list of todo texts like

['wash dishes', 'have some coffee']
, instead of using objects which complicate the logic for a basic todo app.

Here's a recommended approach:

addToLocalStorage function:

function addToLocalStorage(todo) {
  todo.push(input.value);
  localStorage.setItem('TODO_LIST', JSON.stringify(todo));
}

getFromLocalStorage function:

function getFromLocalStorage() {
  // this retrieves a stringified array of todos
  const reference = localStorage.getItem('TODO_LIST');

  if (reference) {
    todos = JSON.parse(reference);
    renderTodo();
  }
}

I hope this information proves helpful.

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

Why is the quantity of cookies in the "Cookie" request header greater than the amount of cookies defined in the "set-cookie" response header?

I am new to the world of web scraping and still have a lot to learn about HTTP requests. As I examine the requests I make, like adding items to a cart on a website, using developer tools, I notice that the "Cookie" header in the request contains more value ...

The child component emitted a custom event, but the listener in the parent component was not activated

I've created a child component in Vue that emits a custom event, however the listener in the parent component is not being triggered. <template id="add-item-template"> <div class="input-group"> <input @keyup.enter="addItem" v-model=" ...

Extract a portion of a phrase from a specified component

I've been using the wpdiscuz plugin for WordPress and I'm looking to remove a specific part of the content within the .wc-comment-title element. Specifically, I want to use jQuery or JavaScript to delete a portion of a sentence within a paragraph ...

What is causing this JSON to malfunction in Internet Explorer?

Everything is functioning well on Chrome and other browsers except for IE. Below is an example to illustrate: (specifically referring to IE 8, unsure about compatibility with IE 9) Upon running the JSON request, I encountered an error stating "Object exp ...

When I prevent 3rd party cookies, the Google Signin onsuccess function remains inactive

I've been working on an AngularJS application that utilizes the basic Google Signin process outlined here: https://developers.google.com/identity/sign-in/web/. Everything is functioning properly, and I'm able to sign in as a Google user. However ...

Executing a PHP function with an onclick event on an `<li>` tag via AJAX: What's the best approach?

Can you assist me in using AJAX to call a PHP function that communicates with an external server when the onclick event is triggered? <div class="container"> <h3 style=color:blue;>DETAILS </h3> <ul class="nav nav-pills" style="backgro ...

Error message "Function pointer is not a valid function" encountered in Angular version 1.2.25

I am encountering this error sporadically and without any specific pattern. Previously, the page was functioning correctly, but now this error is causing disruptions. Is there a recommended method for debugging or tracing the source of this problem? Err ...

Guide to saving the output of fgets into a character array

I am encountering the below error message: Process terminated with status -1073741819 I have a suspicion that it might be due to my fgets() function, but I am unsure of the cause. Any assistance in resolving this issue would be greatly appreciated. //Re ...

Can you show me how to divide a number by a comma after every two digits and then save the result into two separate

Given a variable var Number = 2425;, the task is to split it into two parts and store them in separate variables. var data = 24; var month = 25; What would be the most efficient way to achieve this using JavaScript? ...

What is the best way to showcase the information from DataProvider in Amcharts visualizations directly beneath each chart?

After creating some graphics using Amcharts, I encountered a challenge in displaying the table of data (dataProvider) right below each graph on my HTML page. Despite searching extensively for a solution, I have been unable to find one. The table of data ...

"Discover the steps to seamlessly integrating Snappuzzle with jQuery on your

I am a beginner when it comes to javascript and jquery, and I recently came across the snappuzzle plugin which caught my interest. After visiting snappuzzle plugin, I decided to download and link jQuery, jQuery UI, and the snappuzle.js in my HTML file. I a ...

Should I choose JavaScript or TypeScript for Angular 2.0?

What is the best approach for creating an Angular 2.0 application? Should it be done with JavaScript or TypeScript? I'm struggling to get started with Angular 2.0 using TypeScript, as it's quite different from JavaScript. ...

Open $_POST in a new tab that has been edited for your convenience

<form method="post" target="_blank" action="battle.php" onsubmit="window.open('battle.php','','width=700,height=500,toolbar=0,menubar=0,location=0,status=0,scrollbars=0,resizable=0,left=30,top=0');" > < ...

What steps can I take to correct my code so that it only shows a single table?

I'm facing an issue while trying to display my dynamic JSON data. It's rendering a table for each result instead of all results in the same table. My array data is coming from the backend API. const arr = [ { "Demo": [ ...

Is there a way to efficiently resize a collection of 2D arrays (stored as a 3D array) using a 2D array in NumPy for vectorized operations?

I have a 3D array consisting of N x N covariance matrices for M channels [M x N x N]. Additionally, I possess a 2D matrix containing scaling factors for each channel at various time points [M x T]. My goal is to generate a 4D array that includes a scaled v ...

Synchronize movie subtitles with precision using javascript

Currently, I am facing a challenge with syncing my JSON subtitle with an iframe video from YouTube. Unlike the typical formats such as vtt and srt, I prefer writing my subtitles in JSON format. My main query revolves around how to accurately sync my JSON ...

When encountering an issue while invoking a function in Vue.js, an internal error may occur, as evidenced by the message: "new Http

Currently, I am in the process of developing an application and encountering an issue where I am unable to comprehend a cryptic error message that keeps popping up. If you'd like to see the error itself, you can check it out here. Below is my form.vu ...

Utilizing JavaScript to retrieve data from a self-submitting form

From my database, I am able to create a list of options for users to choose from. Once a selection is made, the values are submitted back to the same page and retrieved using Javascript. Within the same form, there are radio buttons and a multiple selecti ...

Displaying JavaScript - Nothing to Echo in PHP

Using PHP to echo a JavaScript block, I have encountered an error message. echo "<script language='javascript' type='text/javascript'> jQuery(document).ready(function($){ var $lg = $('#mydiv'); ...

Tips for modifying the data content color of a vis.js timeline

In my Vue.js application, I am utilizing the vis.js timeline to display data. I have incorporated the vis timeline with randomly generated data. Here is the code snippet: created() { var now = moment().minutes(0).seconds(0).milliseconds(0); var g ...