Ionic - Deleting an item from local storage

Currently, I am implementing local storage for my Ionic application. While I can successfully add and retrieve data from local storage, I encounter an issue when trying to delete a specific object - it ends up removing everything in the database. Moreover, attempting to add a new object to the now empty database results in the following error message: "Runtime error - Cannot read property 'push' of undefined"

The intended user scenario for the app involves a user adding a favorite TV show to a favorites list and having the option to unfavorite it if desired.

Below is the code snippet from my service that contains the functions for handling local storage:

export class FavoritesService{

  constructor(private storage: Storage){}
  public favoritesSeries: any = [];

  addSeriesToFavorites(serie: any)
  {
    this.favoritesSeries.push(serie);
    console.log('Add to');
    console.log(this.favoritesSeries);
    this.storage.set('FavSerie',this.favoritesSeries);
  }

  getFavoriteSeries(){

      this.favoritesSeries = [];

      this.storage.get('FavSerie').then((val) => {
        console.log(val);
        if (val){
          this.favoritesSeries = val;
        }});
  }

  removeFavoriteSeries(){
    this.storage.remove('FavSerie').then((val)=>{
      this.favoritesSeries = val
      console.log('serie is removed');
    });
  }

  saveChanges(favoriteSeries: any) {
    this.favoritesSeries = favoriteSeries;
    this.storage.set('favoriteSeries', this.favoritesSeries);
  }
}

The favorites page code snippet:

export class Favorites {

  series: {};

  constructor(public navCtrl: NavController,
              public navParams: NavParams,
              public seriesService: SeriesService,
              public alertCtrl: AlertController,
              public favoritesService: FavoritesService) {
  }

  ionViewDidLoad() {
    //displays the favorite series
    this.series = this.favoritesService.favoritesSeries;
    console.log(this.favoritesService.favoritesSeries);
    console.log(this.series);
  }

  onRemoveFromFavorites(FavSerie: any){
    const alert = this.alertCtrl.create({
      title: 'Remove From Favorites',
      subTitle: 'Are you sure?',
      message: 'Are you sure you want to remove from favorites?',
      buttons: [

        {
          text: 'Yes',
          handler: () => {
            console.log('OK');
            console.log(FavSerie);
            this.favoritesService.removeFavoriteSeries();
            console.log('after service addToFavorite');
          }
        },
        {
          text: 'No',
          role: 'cancel',
          handler: () => {
            console.log('Cancel');
          }
        }
      ]
    });
    alert.present();
  }
}

Answer №1

Here's how you can optimize the way you handle your data:

  • Make changes to the favoritesSeries
  • Store the updated favoritesSeries as FavSerie

Your current method, removeFavoriteSeries, functions in this manner:

  • Delete the FavSerie (which is essentially your series array) from the database
  • Assign the result of the promise returned by storage.remove to the favoritesSeries

To enhance your code, consider modifying your removeFavoriteSeries like so:

removeFavoriteSeries(serie: any){
    this.favoritesSeries = this.favoritesSeries.filter(s => s !== serie);
    this.saveChanges(this.favoritesSeries);
}

This updated function accomplishes the following:

  • Modifies the favoritesSeries list that houses all the series
  • Saves the altered favoritesSeries to storage

This approach aligns with the rest of your code that manages the series list.

After implementing the revised removeFavoriteSeries method, it will effectively remove the specified serie.

As a suggestion, it may be beneficial to define a specific type for your serie object to catch potential errors at compile time when dealing with favoritesSeries as an array of fixed types.

Note:

You should update the onRemoveFromFavorites within your Favorites class:

Instead of

this.favoritesService.removeFavoriteSeries();
, use
this.favoritesService.removeFavoriteSeries(FavSerie);
.

By doing this, you pass the series you wish to remove to your FavoritesService.

Furthermore, adjust your addSeriesToFavorites as follows:

addSeriesToFavorites(serie: any)
{
    this.favoritesSeries.push(serie);
    console.log('Add to');
    console.log(this.favoritesSeries);
    this.saveChanges(this.favoritesSeries); // <- utilize the saving method

}

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

Windows authentication login only appears in Chrome after opening the developer tools

My current issue involves a React app that needs to authenticate against a windows auth server. To achieve this, I'm hitting an endpoint to fetch user details with the credentials included in the header. As per my understanding, this should trigger th ...

A circular reference occurs when a base class creates a new instance of a child class within its own definition

My goal is to instantiate a child class within a static method of the base class using the following code: class Baseclass { public static create(){ const newInstance = new Childclass(); return newInstance; } } class Childclass ex ...

Align the ion content (or text or label) to the center vertically

I am striving to achieve a similar look as shown in the following images: However, I am currently at this stage: Please note that the first image showcases a bootstrap form, while the second image displays my design using ionic. Although I prefer not to ...

How can you determine if an API method call has completed in Angular and proceed to the next task?

Two methods are being used for api calls in my code. Method one is calling out method two and needs to wait for method two's api call to finish before continuing with its own process. I attempted to achieve this using the complete function inside a su ...

Dynamically loading external JavaScript for an Angular component and triggering the window load event

I am currently dealing with an external javascript file that I only want to be included on a specific component, so the approach I'm taking involves dynamically loading it. I came across this answer that explains exactly how to achieve this. The prob ...

A guide on organizing similar elements within an array using Angular

Could you assist me in grouping duplicate elements into separate arrays of objects? For example: array = [{key: 1}, {key: 5}, {key: 1}, {key: 3}, {key: 5}, {key: 1}, {key: 3}, {key: 2}, {key: 1}, {key: 4}]; Expected output: newArrayObj = {[{key: 1}, {key ...

How to utilize *ngFor alongside the async pipe for conditional rendering in Angular 8 HTML

.html <ng-container *ngFor="let contact of listContact | async; let index = index;"> <h6 class="title" *ngIf="contact && contact['type']"> {{contact['type']}} </h6> <div> {{conta ...

Having trouble linking the date object with the default value of the date input field

Exploring how to set the default value of a date type input using property binding. Initially, I attempted to create a new date object in app.component.ts and then bind the [value] attribute of the date input to the currentDate property within app.compone ...

typescriptCreating a custom useFetch hook with TypeScript and Axios

I have a query regarding the utilization of the useFetch hook with TypeScript and Axios. I came across an example of the useFetch hook in JavaScript, but I need help adapting it for TypeScript. The JavaScript implementation only handles response and error ...

Check out the attributes of a class

I have a TypeScript class that is defined like this: export class MyModel { ID: number; TYPE_ID: number; RECOMMENDED_HOURS: number; UNASSIGNED_HOURS: number; } In a different .ts file, I instantiate this class within a component: export class My ...

The utilization of the Angular date pipe significantly impacts the way dates are

When I use the pipe date:'MM/dd/YYYY' to display the date 2022-01-01T00:00:00, it shows as 1/01/2021 instead of 1/01/2022. This issue only occurs with this specific date. Why does this happen? The value of pharmacyRestrictionDate is 2022-01-01T0 ...

Error: Unable to locate the tslint command

After attempting to utilize tslint --fix, I encountered the error message bash: tslint: command not found.... To install tslint, I ran the following command: yarn global add tslint typescript. The operating system on my machine is Centos 7. ...

The Angular Animation constantly resets with each new action taken

In my Angular project, I am working on a scaling animation for a list. I want the animation to only trigger when specific buttons (red and green) are pressed. Currently, the animation restarts regardless of what I click on. Can anyone help me troubleshoot ...

Is it possible to enhance an external class with a non-static method using prototypes?

Is it possible to use prototypes to add a function for a class instance? allowing me to access this or __proto__ keyword inside my method, like so: class PersonClass { name: string; constructor(name: string) { this.name = name; } sayHello() ...

Oh no, an issue has occurred with The Angular Compiler! It appears that TypeScript version 3.9.10 was found instead of the required version, which should be >=3.6.4 and <

After upgrading my angular application from version 5 to version 9, I encountered an issue while trying to deploy my code on the server. ERROR in The Angular Compiler requires TypeScript >=3.6.4 and <3.9.0 but 3.9.10 was found instead. Even though ...

What could be causing the "Error: InvalidPipeArgument" to appear in my Angular code?

Currently, I am tackling a challenge within my Angular project that involves the following situation: Essentially, my HomeComponent view code looks like this: <div class="courses-panel"> <h3>All Courses</h3> <mat-t ...

What purpose does a private property serve within the interface?

Given the following code snippet: class X { bar() { return "bar" } constructor(private readonly x: number){} } interface Y extends X { } const f = (y: Y) => { console.log(y.bar()); } f({ bar: () => "tavern"}); The code does ...

Unique: "Unique One-Step Deviation in Date Comparison"

A Little Background Information: I am working with data points that span from the current day to 5 days ahead, in 3-hour intervals (such as 10pm, 1am, 4am, 7am...). My goal is to organize these data points into arrays sorted by date, with each array repre ...

Exploring Angular Testing with SpyOn

Apologies for my inexperience with Angular, but I am struggling with using spyOn in a unit test. In my unit test, there is a method on the component that calls service1, which in turn calls another service2. However, when I try to spyOn service1 in order ...

What is the best approach to creating multiple dropdowns in ant-design with unique options for each?

It seems like I may be overlooking a simple solution here. Ant-Design dropdowns utilize an array of ItemProp objects to show the options, but this restricts me to having only one list of options. const choices: MenuProps['items'] = [ { label: ...