It seems that every time you save data in Angular, the local storage array gets overwritten

While using Angular, I encountered an issue with saving to local storage. The code works fine for saving items initially, but on refreshing the page and trying to add more objects to the local storage array, it overwrites instead of appending. Can you help me identify where I might be going wrong?

The array public playlist = []; is shared across components through a service, and this is where the objects are being pushed.

component.ts

import { Component, OnInit } from '@angular/core';
import { PlaylistService } from '../../../services/playlist.service';
import { faSave } from '@fortawesome/free-solid-svg-icons';

@Component({
  selector: 'app-playlist-view',
  templateUrl: './playlist-view.component.html',
  styleUrls: ['./playlist-view.component.scss']
})
export class PlaylistViewComponent implements OnInit {

  faSave = faSave;

  constructor(private list: PlaylistService) { }

  ngOnInit() {
        this.list.getPlaylist();

  }
}

Playlist.service.ts

import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class PlaylistService {

  public playlist = [];

  savePlaylist() {
    this.playlist = JSON.parse(localStorage.getItem('playlist'));
    localStorage.setItem('playlist', JSON.stringify(this.playlist));
    console.log('Saved', this.playlist);
  }

  getPlaylist() {
    if (localStorage.getItem('playlist') == null) {
      this.playlist = [];
    } else {
      this.playlist = JSON.parse(localStorage.getItem('playlist'));

    }
  }

  constructor() { 
  }
}

Answer №1

You are observing the process of overriding, which is correct based on the provided code. When saving in localstore, you retrieve the existing data from localstore and then assign it to playlist. Subsequently, you save the updated playlist back into localstore.

The correct approach is to first save the playlist in localstore and then assign it to the class-level playlist.

The modified savePlaylist function should be as follows:

Playlist.service.ts

savePlaylist() {
    // Saving the data first 
    localStorage.setItem('playlist', JSON.stringify(this.playlist));
    // Retrieving the saved data afterwards
    this.playlist = JSON.parse(localStorage.getItem('playlist'));
    console.log('Saved', this.playlist);
}

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

What is the best way to exclude a particular subtype or property?

Is there a way to exclude a specific nested property? Let's take a look at an example. interface ILikes { article: string, page: string, userId: number | string, } interface IUserData { userName: string, isAdmin: boolean, ...data, ...

An unexpected error has occurred in Angular 2 while referencing the service proxy with code asd:18. The error message is: (SystemJS) Unexpected token < SyntaxError: Unexpected token

Forgive me for asking what may seem like a silly question. I am a newcomer to Angular 2 and encountering some problems with the API that my app is utilizing. The consumed Web API is located within the following folder structure: - src - app - Regist ...

Encountering an unexpected token error when using Typescript with Next

Currently, this is what I have in my _document.tsx file: import Document, { Html, Head, Main, NextScript } from 'next/document'; class CustomDocument extends Document { return = (): JSX.Element => ( <Html lang="en-US"> ...

The ag-Grid cellDoubleClicked event seems to be triggered twice when the cell is double clicked quickly, but functions correctly when double clicking at a slower

Currently, I am facing an issue in my Angular 8 project while using Ag-grid. The problem arises when I try to handle the double click event in ag-grid. Whenever the cellDoubleClicked event is triggered, a method is called twice if I quickly double click on ...

Achieve validation of numerous variables without the need for a string of if-else

If we have three variables, such as firstName, lastName, and email, how can we check if they are empty or not without using multiple if else blocks? let firstName = "John"; let lastName = "Doe"; let email = "john.doe@example.com"; if (firstName.trim() == ...

Implement the click event binding using classes in Angular 2

If I have the template below, how can I use TypeScript to bind a click event by class? My goal is to retrieve attributes of the clicked element. <ul> <li id="1" class="selectModal">First</li> <li id="2" class="selectModal">Seco ...

Creating an Angular table row that can expand and collapse using ng-bootstrap components is a convenient and

I need assistance with an application I am developing, where I want to expand a table row to display details when it is clicked. The issue I am facing is that currently, all rows expand and show the data of the clicked row as seen in the image result below ...

"Enhancing user experience with MaterialUI Rating feature combined with TextField bordered outline for effortless input

I'm currently working on developing a custom Rating component that features a border with a label similar to the outlined border of a TextField. I came across some helpful insights in this and this questions, which suggest using a TextField along with ...

Guide on launching an Angular 12 project with the help of Angular CLI 13

After downloading an Angular 12 project, I attempted to run it using Angular 13 (the latest version). However, I encountered issues when trying to run it. Even after attempting to use npm install, I still faced dependency problems. Errors occurred when ru ...

Steps for fixing the error message "Type 'Observable<string>' is not assignable to type 'Observable<{ userId: string; partyId: string; }>'"

Having some trouble with my Angular project. I have this code snippet in my getUser() method, but the compiler isn't happy about it and I can't seem to figure out what's wrong: public getUser(): Observable<{ userId: string; partyId: strin ...

What is the best way to perform a deep copy in Angular 4 without relying on JQuery functions?

Within my application, I am working with an array of heroes which are displayed in a list using *ngFor. When a user clicks on a hero in the list, the hero is copied to a new variable and that variable is then bound to an input field using two-way binding. ...

What causes a function loss when using the spread operator on window.localStorage?

I am attempting to enhance the window.localStorage object by adding custom methods and returning an object in the form of EnhancedStorageType, which includes extra members. Prior to using the spread operator, the storage.clear method is clearly defined... ...

How can you implement a null filter in the mergeMap function below?

I created a subscription service to fetch a value, which was then used to call another API. However, the initial subscription API has now changed and the value can potentially be null. How should I handle this situation? My code is generating a compile e ...

Combine iron-page and bind them together

Recently, I've started learning about Polymer and I want to bind together paper-tabs and iron-pages so that when a tab is clicked, the content loads dynamically. After going through the documentation, this is what I have tried: <app-toolbar> ...

Send the user to an Angular route once they have successfully authenticated with Google

I'm facing an issue with redirecting users to an Angular route. Here's the scenario: When I'm on the login page and click on Google login, I get redirected to Google for authentication. After successfully logging in, I want to be redirecte ...

I'm trying to resolve the "Uncaught TypeError: Cannot read property '0' of null" error that keeps popping up in my Mobx action within a Firebase and React application. Can anyone offer some guidance on

I've encountered some errors while working on a Mobx React application that occurs when I navigate to the /login page, despite being logged in. Here's a snippet of my code: index.tsx (Code Snippet Here) App.tsx (Code Snippet Here) Login.tsx ...

Limit the category to a specific subset of strings

Looking for a way to implement literal type restrictions without using type aliases: const foo = (a: 'string', b: 'string') => { } foo("123", "abc") // should fail foo("123" as 'string', "abc" as 'string') I pr ...

The jQuery method .on gathers and retains click events

I created a component that manages a view containing articles with games. In order to prevent memory overload and optimize performance, I implemented a solution where when a user clicks on an article (each having the class "flashgame"), they can choose to ...

Transfer items on a list by dragging and dropping them onto the navigation label of the target component

I'm currently exploring how to move an element from a list to a <div> and then see it transferred to another list. The objective is to allow users to drag items from one list onto the labels in a sidebar navigation, causing the item to switch t ...

Dynamically loading components within an Angular application

I am tasked with displaying different components at specific times by iterating through them. Below is an example of how I have attempted to achieve this. The components I can use are determined by the server. <ngb-tabset [activeId]="1"> ...