Removing items from an array within an object stored in local storage using an Ionic application

One of my challenges involves an Ionic App that stores data in the localStorage. I need to remove specific items from an array within an object in the localStorage when a user clicks on them.

Even though I have the code below, it doesn't seem to be functioning properly. Can anyone point out where I might be going wrong?

home.html:

<ng-container *ngFor="let item of items[0]">
    <ion-item no-lines class="items" *ngIf='this.items!= 0' (click)="deletereminder(item)">
        <ion-row>
            <ion-col>
                <h3 ion-text class="items">
                    Reminder {{item [0] + 1}}
                </h3>
            </ion-col>
            <ion-col>
                <h3 ion-text class="items">
                    {{item [1] | date:'medium'}}
                </h3>
            </ion-col>
            <ion-col style="text-align: right;">
                <h3 ion-text class="itemdelete">
                    <ion-icon name="trash"></ion-icon>
                </h3>
            </ion-col>
        </ion-row>
    </ion-item>
</ng-container>

home.ts:

 deletereminder(item){
    var newObj = JSON.parse(localStorage.getItem('Data'));
    console.log("index to delete",item);
    newObj.data.splice(item, 1)
    localStorage.setItem('Data', JSON.stringify(newObj));
  }

This is what my localStorage looks like:

Key   : Data
Value : {"data":[[0,"1600074900000"],[1,"1600679760000"]]}

The issue with the above home.ts file is that instead of deleting the clicked item, it's removing the entire array. The function

(click)="deletereminder(item)"
does provide the correct item to be deleted when tested with console.log(item), but it strangely deletes items starting from the top of the array downwards. Moreover, it fails to delete the last record when reached.

Answer №1

To update the value in your localStorage, simply set it again with the new data key instead of using removeItem() which only removes an item by key from localStorage:

  1. const newObj = localStorage.getItem("Data")
  2. Remove the index from object
  3. localStorage.setItem("Data", newObj )

It's recommended to use JSON.stringify when storing objects in localStorage like this:

localStorage.setItem('Data', JSON.stringify( {"data":[[0,"1600074900000"],[1,"1600679760000"]]}));

To retrieve and modify the stored object, you can do something like this:

let DataObj = JSON.parse(localStorage.getItem('Data'));

If you are using JSON.stringify() in your home.ts to store, try implementing the following:

home.ts

deletereminder(item){
  let newObj = JSON.parse(localStorage.getItem('Data'));
  newObj.data.forEach((element, index) => {
    if(element[0] == item) {
       newObj.data.splice(index, 1)
    }
  })
  localStorage.setItem('Data', JSON.stringify(newObj));
}

Answer №2

I successfully resolved the issue by implementing the updated code below.

Changes made in home.html:

<ng-container *ngFor="let item of items[0]; let index = index" >
    <ion-item no-lines  class="items"  *ngIf='this.allObj1 != 0' (click)="deletereminder(index)">

Changes made in home.ts:

deletereminder(index){
    var newObj = JSON.parse(localStorage.getItem('Data'));
    var indextodelete = index;
    newObj.data.splice(indextodelete, 1)
    localStorage.setItem('Data', JSON.stringify(newObj));
}

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

Using Iframe for WooCommerce integration and implementing Facebook login within an Ionic application

I have created an Ionic application that includes an iframe from a Wordpress website. Here is the code snippet from my home.page.ts file: import { Component } from '@angular/core'; import { DomSanitizer } from "@angular/platform-browser"; @Com ...

Typescript raises an issue regarding a React component's optional prop potentially being undefined

I have a basic React component that looks like this: interface ComponentProperties { onClick?: () => void; } const CustomComponent = (properties: ComponentProperties) => { if (!properties.onClick) { return <></>; } ...

Is it necessary to use Generics in order for a TypeScript `extends` conditional type statement to function properly?

Looking to improve my understanding of the extends keyword in TypeScript and its various uses. I recently discovered two built-in utilities, Extract and Exclude, which utilize both extends and Conditional Typing. /** * Exclude from T those types that are ...

Tips for circumventing if statements in TypeScript-ReactJS?

I currently have various action checks in place to perform different functions. Essentially, I am using if and else conditions to determine the action type and execute the corresponding functionality as shown below: public onMessage = (messageEvent) => ...

Starting the process of configuring Angular 5 with Express using TypeScript

Hi there! I am looking to create a fresh application using angular 5 and express (typescript for express as well). Do you have any helpful guides or tips that could assist me in reaching my objective? Appreciate all the help, Giuseppe ...

Organizing an array based on designated keywords or strings

Currently, I am in the process of organizing my logframe and need to arrange my array as follows: Impact Outcomes Output Activities Here is the initial configuration of my array: { id: 15, parentId: 18, type: OUTPUT, sequence: 1 }, { id: 16, parentId: ...

Tips for effectively using ngOnChanges in Angular 2 to validate inputs without causing the 'Expression has changed after it was checked' error

I attempted to create my own custom component with basic validation using regex that can be passed as input to the component. There are two scenarios to consider: one where the form is initially empty (new item form) and another where data is already prese ...

Is it possible to utilize the spread operator for combining arrays?

Consider two different arrays represented by variables a and b. The variable c represents the output as a single array, indicating that this method combines two or more arrays into one. let a=[a ,b]; let b=[c ,d]; c=[a,...b] The resulting array will be: ...

update angular component after deleting an item

After deleting a contact in the table, I'm trying to refresh my contact list page but it's not working. Any suggestions? This is the list of contacts in the contact.component.ts file Swal.fire({ title: 'Do you want to delete this contac ...

How can you create an interface where the value type is determined by the key, but not all keys are predefined?

Below is an illustration of a data structure that I aim to define as a type in TypeScript: const dataExample = { Folder: { "Filename.js": { lines: { total: 100, covered: 80, ...

Incorporate new class into preexisting modules from external library

I am currently working on expanding Phaser by incorporating a new module called Phaser.Physics.Box2D. While Phaser already utilizes this module internally, it is an additional plugin and I am determined to create my own version. TypeScript is the language ...

Selecting keys of an object in Angular 2

Attempting to fetch data from an API using key selection but encountering retrieval issues. File: app/app.component.ts import {Component, OnInit} from 'angular2/core'; import {Http} from 'angular2/http'; import {httpServiceClass} fro ...

Encountered an error while attempting to upgrade to the latest @angular/cli version 1.0.0: Unexpected symbol "<" found in JSON at the beginning of the file

When I was using angular-cli 1.0.0 beta 23, my service was able to fetch a local JSON file for testing without any issues. However, after upgrading to angular/cli 1.0.0, I encountered the following problem: GET http://localhost:4200/json/inputInventory/ ...

How to simulate a typescript class using vitest

I am encountering a situation where I have a class A that imports another class B from a separate module and creates an instance of it. While writing tests for class A, I want to stub or mock some of the methods of class B. Below is an example code snippe ...

Is Axios the sole option for API calls when utilizing Next.js with SSG and SSR?

Can someone clarify the best practice for data fetching in Next.js? Should we avoid using axios or other methods in our functional components, and instead rely on SSG/SSR functions? I'm new to Next.js and seeking guidance. ...

Troubleshooting an Integration Problem Between Express and socket.io

Having trouble reaching the io.on('connect') callback in my basic express setup. The connection seems to stall. Node 12.14.1 express 4.17.1 socket.io 3.0.1 code import express, { ErrorRequestHandler } from 'express'; import path from ...

Broaden your interfaces by implementing multiple interfaces with Zod

Utilizing typescript, I am able to incorporate multiple interfaces interface Name { name: string } interface Age { age: number } interface People extends Name, Age { height: number } Is there a similar way to achieve this with Zod? What I attempted ...

Issue: Unable to resolve all parameters for TypeDecorator in Angular 2 RC-6

I've been struggling with this error for more than a day, and I can't seem to figure out the cause. app.module import {NgModule} from "@angular/core"; import {BrowserModule} from "@angular/platform-browser"; import {AppComponent} from "./app.co ...

An issue arose when trying to display React components within an Angular application

Attempting to incorporate React components into an Angular 7 application has been a challenge for me. While I have successfully rendered simple React components, I encountered the following error message (displayed in the browser console) when attempting t ...

Unable to assign user roles in next-auth due to the absence of matching modifiers for user

I am currently working on implementing user roles in next-auth. Within my database, I have defined a prisma enum UserRole with the values 'ADMIN' and 'USER'. In my auth.ts file, I included the role property in the session object and enc ...