Remove the array stored in the local storage of an Ionic 2 application

In my application, I store data in a string.

To convert the data into arrays, I use JSON.parse.

this.items = JSON.parse(todos); 

On the results page, I display my arrays as follows: Array1 Array2 Array3

However, I have noticed that the delete button after each array only removes the item from the list and not from local storage. Is there something wrong with my implementation?

This is the code for list.html:

<ion-item-sliding *ngFor="let item of items">
  <ion-item>
  <p>{{item.amount}}tk X {{item.class}} / {{item.size}}ml / {{item.proof}}%</p>
  </ion-item>
  <ion-item-options>
  <button danger (click)="removePost(item)">
  <ion-icon name="trash"></ion-icon>Remove
  </button>
  </ion-item-options>
  </ion-item-sliding>

And this is list.ts:

removePost(item){
    let index = this.items.indexOf(item);
   if(index > -1){
      this.items.splice(index, 1); // works
      this.storage.remove(this.items[index]); // doesn't work
    }
}

Answer №1

When dealing with a JSON array stored as a string in local storage, it's important to note that simply trying to remove an object directly from the array won't work due to the string nature of the entire local storage value.

To successfully remove an object, you should use the splice method to delete the desired item and then update the local storage by setting it once again with the modified array.

deleteItem(item) {
   let index = this.items.indexOf(item);
   if (index > -1) {
      this.items.splice(index, 1); // works
      //this.storage.remove(this.items[index]); // doesn't work
      localStorage.setItem("name_of_the_storage", JSON.stringify(this.items));
    }
}

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

Monitoring modifications in elements within an array using Angular2

Currently using Angular 2 and typescript, I have an array in which I am utilizing DoCheck and IterableDiffer to monitor any changes. While I receive notifications when the array itself is modified, I do not get notified if a property within one of the obje ...

When the property "a" is set to true, it must also require the properties "b" and "c" to be included

I'm looking for a way to modify the following type structure: type Foo = { a: boolean; b: string; c: string; } I want to change it so that if a is true, then both b and c fields are required. However, if a is false or undefined, then neither b ...

Efficiently utilizing ngrx by orchestrating various services and actions to achieve accurate mapping

Combining multiple effects into one is my current goal due to an issue with dispatching actions separately. The aim is to execute sequentially after verifying the value returned from the first service call. Here are the three separate effects I have: @Eff ...

Angular 6 Error: Template Driven Form - Unable to access property 'required' in null entity

Struggling with validation issues while working on an angular 6 project with a template-driven form. Here is the HTML code snippet causing trouble: <div class="form-group"> <div class="form-group"> ...

When utilizing the OnPush strategy, the view of the child component does not undergo re-rendering

@Component({ selector: "parent", template: `<child [userId]="(userID$ | async)"></child>`, changeDetection: ChangeDetectionStrategy.OnPush }) export class ParentComponent implements OnInit { userID$: BehaviorSubject<string> ...

I'm experiencing a delay in receiving real-time values with Angular Observables

My project involves 2 components (Menu and Header) and one Service. The goal is for the menu to send the selected item text to the service, which will then pass it to the header for display. While I have successfully sent data to the service, I am facing a ...

Is Angular 10 disregarding set-cookie response headers?

After logging in, I attempted to utilize a session auth cookie without success. To troubleshoot, I implemented a basic "CookieTest" method on my Dotnet Core server: [Route("CookieTest")] public ActionResult CookieTest() { var options = new CookieOptions ...

Exploring the Possibilities with Material UI v4: Expanding on PaletteColor

Looking to make a simple adjustment in Material UI v4's (v4.11) palette, specifically adding a new field to PaletteColorOptions like darker?: string. The type definition can be found in the relevant Material UI module: createPalette.d.ts export type ...

Utilize external libraries with Angular 2 for Just-In-Time and Ahead-of-Time compilation techniques

I've been working on setting up my codebase to support both JiT and AoT compilation in order to utilize JiT for local development and AoT for production. Following the Angular documentation, I have successfully configured both modes individually. How ...

An issue arises when trying to access a resolved variable from UI router in a component

I am facing an issue with my UI router state that has a component attached to it: export const exchangeState = { name: 'exchange', url: '/exchange', component: ExchangeMainComponent, resolve: [ { tok ...

Ways to clear a dynamically created multidimensional array

I am currently attempting to remove an element from an array where the value of a specific key (time) meets a certain condition. The code snippet I have been working on is as follows: foreach($_SESSION as $key) { foreach($key['time'] as $keys ...

In order to determine if components linked from anchor elements are visible on the screen in Next.js, a thorough examination of the components

Currently, I am in the process of developing my own single-page website using Next.js and Typescript. The site consists of two sections: one (component 1) displaying my name and three anchor elements with a 'sticky' setting for easy navigation, a ...

To remove items with duplicate keys in PHP, keep only the one with the smallest value

I am facing a challenge with an array that needs to have elements deleted based on certain criteria. Specifically, I want to remove elements from the array that have the same time, keeping only the one with the lowest amount. While I understand the concept ...

"Enhance your slider experience with React Alice Carousel: place dot controls directly over images for

I am currently working with react-alice-carousel and I'm looking to adjust the placement of the dot controllers on the slider. Instead of their current position, which you can see in this image (https://i.sstatic.net/mi6eD.png), I want them to be loca ...

Tips for extracting basic JSON Array in an Android application

I've been trying to figure out how to parse a JSON Array in android. Here's an example of the json object I have: [{"ID":"1","email":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="7f1a121e16133f121e161351121e16"> ...

What is the method for setting autofocus to the first input element within a loop?

I am currently working on a loop to display inputs, and I would like to be able to add focus to the first input element when it is clicked. Does anyone have any suggestions on how I can select that first element and set autofocus on it? ...

Identifying Flaws in Components during Creation with Ready-Made spec.ts Files

Currently, I have embarked on the journey of creating unit tests for my Angular Material project. At the moment, my focus is on testing whether the pre-made spec.ts files for each component are passing successfully. Despite the fact that my project compile ...

What is the best way to retrieve an object in Angular 5?

I am encountering an issue with retrieving an Array in Angular. The problem is that I have to click the button twice to retrieve the Array data. I would like it to work with just one click (refer to the image at the end of the page). @Injectable() export ...

Run a script in a newly opened tab using the chrome.tabs.create() method

Struggling with executing a script using chrome.tabs.executeScript() in the tab created with chrome.tabs.create()? Despite searching for solutions, nothing seems to be working as expected. Check out my current code below: runContentScript(){ c ...

Fixing the issue of 'Unrecognized character < in JSON at position 0 at JSON.parse'

I have recently deployed my Angular 6 application on Heroku at . However, upon deploying, I encountered the error message: SyntaxError: Unexpected token < in JSON at position 0 during JSON.parse. I am aware that this error occurs when the response ret ...