Using browser's local storage: deleting an entry

I recently came across a straightforward to-do list. Although the inputs are properly stored in local storage, I encountered issues with the "removing item" functionality in JS. Even after removing items from the HTML, they still persist in local storage upon refreshing the page, which is puzzling to me. Additionally, I am unsure about the purpose of firstElementChild and why it is included in the code.

/*variables */
const addForm = document.querySelector('.add');
const list = document.querySelector('.todos');
// storing items retrieved from local storage in a variable
let storedItems = localStorage.getItem('tasks');

const generateTemplate = todo => {
    const html = `
    <li>
        <span>${todo}</span>
        <i class="far fa-trash-alt delete"></i>
    </li>`
    
    list.innerHTML += html;
}

if (!storedItems) {
    storedItems = [];
} else {
    storedItems = JSON.parse(storedItems);
    storedItems.forEach(item => {
        generateTemplate(item);
    });
}

addForm.addEventListener('submit', e => {
    const todo = addForm.add.value.trim();
    e.preventDefault();
    if (todo.length) {
        generateTemplate(todo); 
        storedItems.push(todo);
        localStorage.setItem('tasks', JSON.stringify(storedItems))
        addForm.reset();
        console.log(`${todo} has been added to html list`)
        console.log(`Local storage now contains ${storedItems}`)
    }
});

/*Removing item*/

list.addEventListener('click', e => {
    console.log(e.target);
    if (e.target.classList.contains('delete')) {
        e.target.parentElement.remove();
        let removedItem = e.target.parentElement.firstElementChild.innerText;
        console.log(`${removedItem} has been removed from the html list`);
        console.log(storedItems)
        const newArr = storedItems.filter(item => item !== removedItem)
        console.log(newArr)
        storedItems = newArr
        console.log(`Local storage now contains ${storedItems} `)
    }
})
<!DOCTYPE html>
<html lang="en<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.7.2/css/all.css" integrity="sha384-fnmOCqbTlWIlj8LyTjo7mOUStjsKC4pOpQbqyi7RrhN7udi9RwhKkMHpvLbHr" crossorigin="anonymous">
    <title>To-do List</title>
<

Answer №1

When removing items from a local array, remember to update the local storage with the new array. Simply include the following line:

window.localStorage.setItem('tasks', JSON.stringify(storedItems))

This should be placed after:

storedItems = newArr

in your code. Using @TheBritishAreComing's method is ideal when you need to delete the entire list instead of just one task.

Answer №2

This piece of code exclusively focuses on modifying the storedItems array without making any changes to local storage.

if (e.target.classList.contains('delete')) {
        e.target.parentElement.remove();
        let removedItem = e.target.parentElement.firstElementChild.innerText;
        console.log(`${removedItem} has been removed from the html list`);
        console.log(storedItems)
        const newArr = storedItems.filter(item => item !== removedItem)
        console.log(newArr)
        storedItems = newArr
        console.log(`Local storage now contains ${storedItems} `)
    }

Don't forget to incorporate

localStorage.removeItem(removedItem);
before updating your global array.

For more information regarding localStorage.removeItem, refer to the documentation here

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

Is there a way to verify if an array has been initialized and holds a value simultaneously?

Is there a more concise and elegant way to check if ['pk'] exists in the first item of an array before executing certain tasks? The array may not always have data, leading to bloated code. I'm looking for a streamlined solution in Javascrip ...

Internet Explorer 11 XHR Troubles

Our company has successfully developed a JavaScript video player that can be embedded on various websites using a script tag. As part of the bootstrapping process, we utilize XMLHttpRequest to fetch resources from our server. This creates cross-origin requ ...

Can a function be activated in JavaScript when location permission is declined?

Background: Following up on a previous question regarding the use of getCurrentPosition and async functions. I am currently working on The Odin Project and attempting to create a basic weather application. My goal is to include a feature that automatically ...

The compilation process encountered an error: TypeError - Unable to access property 'exclude' as it is undefined (awesome-typescript-loader)

After successfully converting my existing Angular 2 project into Angular 4, I encountered the following error: Module build failed: TypeError: Cannot read property 'exclude' of undefined For more details, please refer to the attached image bel ...

Utilizing jQuery to dynamically add results and prevent duplicate entries in will_paginate

I am currently using will_paginate to easily manage the comments pagination in my Rails 3 application, and so far it's been working flawlessly. At the moment, I have set up the display to show 10 comments per page. However, whenever I add a new comme ...

Is it beneficial to display three.js on a <canvas> rather than a <div>?

I have come across examples in three.js that use: renderer = new THREE.WebGLRenderer( { canvas: document.querySelector( 'canvas' ) } ); This relates to a <canvas></canvas> element. On the contrary, there is another method: rendere ...

Tips for styling a React JS component class

I am attempting to write inline CSS for a React JS component called Login, but I keep encountering an error. What could be causing this issue? Could you provide guidance on the correct way to implement in-line component CSS? import React, {Component} from ...

Encountering an issue when trying to run npm run dev-server on Windows 10

Having trouble running the dev-server for superset-frontend. Encountering this error message. Any assistance would be greatly valued.https://i.stack.imgur.com/zsVU4.png ...

Unable to load page redirection

I am experiencing an issue with this page not redirecting to the appropriate mobile or desktop page when accessed. Below is the code snippet in question: <html> <head> <title>Loading...</title> </head> < ...

conceal parent window element upon clicking an image within an iframe

I'm facing a challenge with hiding certain buttons in a parent window when opening a modal by clicking an image inside an iframe. Below is the code snippet that I am using: In the parent window - <iframe id="gallery" src="links/gallery.html" wid ...

Encountering problems when attempting to effectively filter a list of products using data

<div id="prod"> <div class="content" data-brand="Andrew" data-price="1000" data-store="JCPenny">Andrew</div><br /> <div class="content" data-brand="Hill" d ...

Employing promises for fetching data via XHR results in a promise that is still pending

Currently, I am experimenting with promises to handle asynchronous requests using XHR. Interestingly, I noticed that when I try to log the result within the .then function, it works perfectly fine. However, if I attempt to log it outside of this scope, it ...

Bringing in States and Functions to a React Component

Is there a way to improve the organization of states and functions within a functional React Component? Here's my current code structure: import React from 'react' //more imports... const Dashboard = () => { const [] = useState() / ...

Receiving a 401 error when making an Axios post request

Having trouble with a 401 error when making a POST request to an API? Don't worry, I've got some suggestions that might help. I'm able to successfully make GET requests to the same API with a 200 status, so it could be a syntax issue in the ...

anchor text substitution for hyperlink

I currently have a code snippet that replaces a span class with a hyperlink. The hyperlink contains an abbreviation, and the alternate text for the link also includes the same abbreviation. Now, I am looking to replace the second abbreviation in the alte ...

Struggling to synchronize animation timing between elements using jquery

When you navigate to an album (for example, Nature because I'm still working on the others) and select one of the images, they all gradually fade out while the selected image appears on the screen. What's actually happening is that the selected i ...

Button placed within a jade table cell

I'm struggling to make a button appear in each row of the table. I am new to working with Jade and Node.js, so I can't seem to figure out why it's not showing up. Here is my Jade file: html head body table.table.table(border='1 ...

In what way can you reach an unfamiliar form within a controller?

I am working with multiple dynamically generated forms, each associated with a different model. In my controller, I need to iterate through all the errors within the forms. I assign form names based on the models. <form name="{{myForm}}" novalidate> ...

Guide on securely presenting an HTTP-only cookie as a bearer token, without the use of Angular.JS

Can a JWT be securely stored as an HTTP-only cookie and also used as a bearer token without relying on Angular.JS? I believe this could be achievable, as Angular.JS offers similar features (although I'm not sure if they use an HTTP-only cookie to sto ...

What is the best way to conceal specific series in a HighCharts legend?

In the chart, I currently have 4 series. At the moment, only 2 of them are visible while the other 2 are hidden when the chart first loads. As the user zooms in on the chart, the visibility of the series changes dynamically. I need help figuring out how ...