"Removing an item from an array stored in localstorage: A step-by-step guide

I need to remove an object from an array and also delete it from local storage. I have attempted to use the splice method but am struggling with how to implement it correctly. Below is the code that I have tried:

 var details = [];

function addEntry() {
   var existingEntries = JSON.parse(localStorage.getItem("allEntries"));
   if (existingEntries == null) existingEntries = [];
   
   // Code for adding a new entry to the array and updating local storage
   
   showEntry();
}

function showEntry() {
   // Code for displaying entries in a table format
   
   // Looping through local storage entries
}

// Other validation functions and event handlers...

function deleteEntry(id) {
   // Code for deleting an entry from the array and updating local storage
}

function clearstorage() {
   localStorage.clear();
   window.location.reload();
}

window.onload = function() {
   showEntry();
};

Answer №1

When you call the deleteEntry function, a new item in localStorage called 'entry' is being set. This means that 'allEntries' is not being updated, which may be why it's appearing incorrectly. Make sure to set all entries again by using localStorage.setItem('allEntries', JSON.stringify(entry));

Don't forget to include the '?' for your variable 'entry'...

Here's how it should look: var entry = localStorage.getItem('allEntries') ? JSON.parse(localStorage.getItem('allEntries')) : []; <-- just like this.

This is essentially an 'if else statement'

function deleteEntry(id){
    console.log("aaaaaaaaaaaaaaAAAA");

      var entry = localStorage.getItem('allEntries') ? JSON.parse(localStorage.getItem('allEntries')) : [];
        var index;
        for (var i = 0; i < entry.length; i++) {
            if (entry[i].id === id) {
              index=i;
              break;
            }
        }
        if(index === undefined) return 
        entry.splice(index, 1);
        localStorage.setItem('allEntries', JSON.stringify(entry)); <--- ensure it looks like this

    }

Answer №2

One way to update localStorage is by creating a temporary object and then replacing the existing data with it.

 function removeEntry(id){
    console.log("aaaaaaaaaaaaaaAAAA");

      var entry = JSON.parse(localStorage.getItem('allEntries'));
        var temp= [];
        for (var i = 0; i < entry.length; i++) {
            if (entry[i].id !== id) {
              temp.push(entry[i]);
            }
        }
        localStorage.setItem('entry', JSON.stringify(temp));
    }

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

Node.js routing issues leading to rendering failures

I have been working on a website that involves carpooling with drivers and passengers. When a driver submits their details, they are directed to a URL where they can select the passenger they want to ride with. Here is the code snippet I have written: ap ...

refresh polymer components or make an ajax request within a custom element

I've been spending days on this issue with no success! My application relies on cookies for session handling and includes multiple custom elements imported in the header. Some of these elements need to access information from the 'cookie session& ...

Retrieving the contents of a unique 404 error page using ajax

Currently attempting to retrieve the content of a custom 404 page through ajax (I need to extract a counter value from this page using Greasemonkey). Regrettably, jQuery's .fail method in ajax does not provide the option to access the page's con ...

Alter the hue of a component upon being clicked

Seeking help to modify the color of my menu elements upon clicking on the "center" or "right" containers (reverting back when clicked again). Currently, the three lines in my menu are white, but I desire them to turn red when either of these containers is ...

Analyzing Dynamic Content

Currently, I am engaged in content parsing and have successfully executed a sample program. To demonstrate, I have utilized a mock link which you can access below: Alternatively, you can click on this link: Click Here In the provided link, I have parsed ...

Guide to triggering React Material-UI modal and filling it with data from an Ajax request when a button is clicked

Despite my efforts to find a similar question, I couldn't come across one. My apologies if I overlooked it. Currently, I am working on a React Material-UI project to develop a basic web application. Within this application, there is an XGrid that disp ...

Develop a custom directive that incorporates ng-model and features its own distinct scope

UPDATE - I have generated a Plunker I am in the process of developing a personalized directive to be utilized for all input fields. Each input will have distinct options based on the logged-in user's requirements (mandatory, concealed, etc), so I bel ...

Running npm commands from the root directory while the package.json file is located elsewhere

Although I understand that it's not ideal, I am faced with a specific directory structure that cannot be changed: [projectRootDir] [src] [tests] [otherDirs] [configuration] package.json mocha.opts other files.. ...

Error message: The md-autocomplete function is throwing a TypeError because it cannot read the property 'then' of an undefined object

I am encountering an issue with the md-autocomplete component from angular material. Here is my code snippet: <md-autocomplete required md-search-text="searchTxt" md-selected-item-change="setModelValue(item.name)&q ...

Preventing commits when encountering build or lint errors

Every git repository contains git hooks within the .git/hooks directory. I have included a npm run lint command in the pre-commit git hook. However, I am unable to prevent the commit if npm run lint returns an error. ...

Utilizing a child component in React to trigger a function on its sibling component

Trying to put this question into words is proving to be a challenge. I am wondering in React, if there is a way for a child component that is deeply nested (2 levels deep from the parent) to trigger a function on another component that it has a sibling rel ...

Implementing a play and pause button functionality for the carousel in Bootstrap 5

How can I implement a play/pause feature on the same button when clicking in a Bootstrap 5 carousel using jQuery? **HTML ** <div id="customSlider" class="carousel slide" data-bs-ride="carousel" data-bs-interval="2500& ...

What is the procedure for defining the secret code for a private key in saml2-js?

I need to implement a key/cert with a passphrase in my project that's currently using saml2-js. I have already set up everything but encountering a bad decrypt error without the passphrase. Is there a way to incorporate this passphrase? Below are the ...

Developing a custom logging middleware with morgan

I am trying to develop a middleware using morgan. I have attempted to export the middleware function and then require it in app.js. However, I am facing an issue where it is not working as expected. Middleware: const morgan = require('morgan&apos ...

transform constant values into API requests using React

The sample dataset mentioned will be retrieved from a backend API call handled by Flask. The API has already been configured on the backend. const rows = [ { name: "XYZ", age: "12", email: "<a href="/cdn-cgi/l/emai ...

What is the best way to toggle between rendering two components or updating two outlets based on a route in React Router?

There is a React application I am working on that utilizes React-Router. My layout component has the following structure: import React from 'react'; import Header from './components/Header/Header'; import Footer from './components/ ...

Using dynamic import to pull in the map from an npm package.json in JavaScript

Is there a way to set up path mapping for pure JavaScript imports? Currently, when we want to import npm packages in pure JS without using webpack, the syntax is different. Instead of just using import package from 'package-name', we have to use ...

Understanding how to efficiently map through FontAwesome icons using React TypeScript and effectively showcase them on the frontend

I am in the process of developing a versatile component that allows me to input the href, target, and rel attributes, along with specifying the FontAwesome Icon I want to utilize. My goal is to be able to pass multiple icons into this list, which will then ...

Navigating using Backbone Marionette URL to Server Endpoint

I need to implement client-side validation to check if the user is logged in, and if not, redirect them to the sign-in page. The issue is that the sign-in page exists outside of my Backbone Marionette app. Is there a way in Marionette, Backbone, jQuery, or ...

How do I execute 2 functions when the button is clicked?

<button id="take-photo"> Take Image</button> <button type="submit" value="Submit" >Submit </button> How can I trigger two tasks with a single button click? 1. Executing a function based on ID Next 2. Submitting the form with ...