To-do list application: organizing tasks into local storage for easy access

Struggling to make a todo-app function properly with localstorage, I'm a bit lost on the process. The app is built within a Vue.js project using a main.js file that connects two Classes: App.js and Todo.js (see below).

import App from "./classes/App.js";
const app = new App();

Here are the issues I've encountered:

  1. I can only seem to store one of my added todo's in my storage.
  2. I am unable to retrieve it from my storage and it doesn't load when I reload the page.

Any help would be greatly appreciated, I really want to understand this!

For a cleaner view, here's my CodeSandbox link: Link to my CodeSandbox

And below are the contents of the two js files: App.js

import Todo from "./Todo.js";

export default class App {
  constructor() {
    console.log("🍕");
    this.setupEventListeners();
    this.loadFromStorage();
  }

  setupEventListeners() {
    console.log("👂🏽");
    document
      .querySelector("#add-item-text")
      .addEventListener("keyup", this.createItem.bind(this));
  }

  createItem(e) {
    if (e.key === "Enter") {
      console.log("📕");
      let inputText = document.querySelector("#add-item-text").value;
      let todo = new Todo(inputText);
      todo.add();
      todo.saveToStorage();
      this.reset();
    }
  }

  loadFromStorage() {
    const ref = localStorage.getItem("todo");
    if (ref) {
      todo = JSON.parse(ref);
    }
  }

  reset() {
    document.querySelector("#add-item-text").value = "";
  }
}

Todo.js

    export default class Todo {
  constructor(title) {
    this.title = title;
  }

  createElement() {
    let li = document.createElement("li");
    li.innerHTML = this.title;

    if (li.innerHTML.includes("high:")) {
      li.classList.add("prior-high");
    } else if (li.innerHTML.includes("medium:")) {
      li.classList.add("prior-medium");
    } else if (li.innerHTML.includes("low:")) {
      li.classList.add("prior-low");
    } else {
      li.classList.add("prior-medium");
    }

    li.addEventListener("click", this.markDone);
    return li;
  }

  markDone(e) {
    if (document.querySelector("li").classList.contains("done")) {
      document.querySelector("li").remove();
      window.localStorage.removeItem("li");
    } else {
      document.querySelector("li").classList.add("done");
    }
  }

  add() {
    let todo = this.createElement();
    document.querySelector("#todo-list").appendChild(todo);
  }

  saveToStorage() {
    let myStorage = window.localStorage;

    myStorage.setItem("todo", JSON.stringify(this.title));
  }
}

Answer №1

Storing data in localStorage using

myStorage.setItem("todo", JSON.stringify(this.title))
only saves the title under the key "todo". Repeating this line will overwrite the existing value.

To save multiple TODO item titles, each one should have its own unique key:

myStorage.setItem("todo-key1", todo1.title)

You can also store them as a collection:

myStorage.setItem("todos", JSON.stringify([todo1.title, todo2.title]))

However, adding a new todo requires reading the current values before updating:

myStorage.setItem("todos", JSON.stringify(JSON.parse(myStorage.getItem("todos")).push(newTitle)))

Using helper functions can simplify and improve the readability of your code.

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

Bring together a set of elements within a collection of identical entities that contain corresponding key-value pairs by utilizing JavaScript

Looking at the object below: a = [ {id: 1, comp: 'ans', stat: 'www', value: ['1', '2']}, {id: 2, comp: 'qsn', stat: 'xxx', value: ['a', 'b']}, {id: 3, comp: 'ans', ...

Upload dojo.js to my server for use

Check out this link for a working example: It's functioning perfectly. I then copied the HTML and tried running it on my local Apache server. Surprisingly, it worked! However, when I attempted to load the same dojo.js file on my web server, it ...

A guide to displaying a countdown timer in an Angular application during the app's loading process

Displaying a loader that shows the time in seconds while loading an app is my goal. Here is the code snippet: HTML <body> <div class="app-loader"> <div class="loader-spinner"> <div class="loading-text"></div> ...

Spin a collection of shapes with text while maintaining the text's center and horizontal alignment

It seems like just basic math to me. I'm utilizing Konva to dynamically create shapes, which are saved as a label. This label contains a text element and a rectangle. My goal is to ensure that the text inside the rectangle is always a) centered both ...

Tips for showcasing a drop-down menu using Jquery

I am currently utilizing jQuery to showcase a drop-down menu. It is successfully working for a single menu and displaying the appropriate drop-down. However, when I attempt to use more than one menu, it displays all of the drop-down menus simultaneously. I ...

Utilizing a function upon page initialization in VueX

I am currently learning Vue with Vuex and I have created a method called 'llamarJson' which is used to retrieve JSON data. However, I am facing difficulties in using this method when the page loads. I have tried various approaches but have not be ...

JQuery datepicker - showcase selected date from the datepicker on a calendar view

Is it possible to highlight the dates selected by two different associates on associate.html in training.html? The scenario is that two associates choose their training dates and these specific dates should be highlighted on the training calendar. associa ...

Ways to verify the $window variable in ng-if or ng-show

One variable named variable1 has been declared, and I am looking to validate this variable across all pages using ng-if or ng-show. ...

Learn the steps to export a constant value in Next.js using React!

I need to export the constant value views from BlogPost.js to blog.js. This is the content of BlogPost.js: import React from 'react'; import useSWR from 'swr'; import format from 'comma-number'; import { useColorMode, He ...

Can you share the updated class name for indicating errors in input groups in Bootstrap 4?

I am currently working on creating a form. I want to implement a feature where incorrect data entered will be highlighted in red, and correct data entered will be highlighted in green. This is the code snippet from my .js file: function checkForm() { v ...

The sign-up modal will refresh and then close when an API call is triggered upon submission in Next.js

Within my modal component, I have incorporated a feature that displays either a sign-in or sign-up form based on certain conditions. However, I am facing an issue where upon clicking the submit button on any of these forms, the modal closes regardless of t ...

Creating a map-like scrolling feature for a full-sized image, allowing both horizontal and vertical movement

My goal is to create an infographic image that can be scrolled horizontally and vertically, zoomed in or out, and where I can add markers just like Google Maps. I attempted the solution of using two scroll views as suggested here: https://github.com/faceb ...

I am creating an HTML page that incorporates p5.js, and the text I'm rendering

It seems like the draw loop is continuously refreshing every x seconds, causing this behavior. Is there a way to slow down or disable the frame update without affecting the video refresh rate? I was thinking of adding an fps counter and implementing an i ...

send the variable to the deferred done function

Having trouble passing a variable into a done callback. var getDataForCompany = function(company_id) { $.ajax({ type: "post", url: url, data:{ company_id: company_id } }).done(function(returnedData, textStatus, j ...

What could be causing the failure to retrieve the salt and hash values from the database in NodeJS?

My current issue involves the retrieval of hash and salt values from the database. Although these values are being stored during sign up, they are not being retrieved when needed by the application. Below, you will find snapshots of the database, console s ...

Compare and contrast JSON files that are constantly changing using JavaScript

I have reviewed the various inquiries on comparing JSON objects and feel confident in my ability to implement a comparison. However, my question pertains to dynamically loading source .json files into JSON objects for comparison. The scope of my project h ...

Running a Node.js script on an Express.js server using an HTML button

I've got an HTML button: <button id="save" type="button" onclick="save()">Save</button> and in my JavaScript code, I want it to execute something on the server side using node.js Here's what I have in mind: function save() { / ...

Utilizing the nested combination of map and filter functions

Struggling to grasp the concept of functional programming in JavaScript, my aim is to extract object boxart items with width=150 and height=200. Console.log(arr) the output shows [ [ [ [Object] ], [ [Object] ] ], [ [ [Object] ], [ [Object] ] ] ] I&apos ...

"Transferring information from Ruby to Javascript in Rails: A step-by-step guide

In my Rails 4 application, I am fetching data from the Last_fm API using HTTParty in one of my controllers. The user inputs a city, and I have designed an HTML page to display details of upcoming concerts in that city in a table format, including title, da ...

Using setInterval to update the content of a Text Area continuously

I am currently working on a script that involves extracting a string from a textarea, breaking it down into an array using the delimiter "=====\n", and then displaying each element of the array in the textarea every 250ms. However, I have noticed that ...