Storing data in local storage while using arrays

  public arraySuccess = [];

  ngOnInit(): void {
    this.arraySuccess = JSON.parse(localStorage.getItem('success'));
  }
  openDialog(String) {
    this.dialog.open(RecommendationsDialog);

    if(this.arraySuccess != null && 
       this.arraySuccess.includes(String)) {
      return
    } else if (this.arraySuccess != null) {
      this.arraySuccess.push(String);
    }

    localStorage.setItem('success', JSON.stringify(this.arraySuccess));
    console.log(this.arraySuccess);

  }

I have a total of 3 articles. Whenever they are opened, I want to store their names in the localstorage. When the user revisits the page, I want to display a read checkbox next to the article's name (checking if the name is in the localstorage array).

However, I am facing an issue where I see null in the console.

Can anyone help me find my mistake?

Answer №1

Dealing with Null Values

When using localStorage.getItem(), keep in mind that it can return a value or null. To ensure arraySuccess is always an array, consider checking and initializing it before using the push method :

this.arraySuccess = JSON.parse(localStorage.getItem('success')) ?? [];

This approach guarantees that even if null is returned, your element will still be saved.

In addition, make sure to declare your variable properly (as opposed to String) :

openDialog(myString: string) {
    this.dialog.open(RecommendationsDialog);
    if(this.arraySuccess.includes(myString)) {
      return
    } else {
      this.arraySuccess.push(myString);
    }
    localStorage.setItem('success', JSON.stringify(this.arraySuccess));
  }

Cheers

Note: updated handling of null values as suggested by Heretic Monkey

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 retrieve the `any` type when utilizing the `keyof` keyword?

I am struggling to articulate this question properly, so please refer to the code below interface TestParams<T> { order?: keyof T attr1?: number attr2?: string } async function Test<T = any>(_obj: TestParams<T>): Promise<T> { ...

The integration of react-color Saturation with @types/react-color is currently unavailable

In my quest to develop a customized color picker, I am utilizing the react-color library (^2.19.3) together with @types/react-color (^3.0.4). The issue arises when trying to import the Saturation component since it is not exported from the types in the ind ...

Is there a way to specifically choose the initial element using Angular? "Backend powered by Django"

Hi there! I've set up Django on the back-end to send data to Angular, and I'm trying to display only the first comment from a list in my HTML page. However, when using limitTo, I encountered this error: Failed to compile. src/app/app.component. ...

Encountering an error while attempting to set up WebDriverIO with Typescript and Cucumber installation

After completing the project setup, the wdio.conf.ts and tsconfig.json files are saved in a folder named tests. However, the wdio.conf.ts file throws an error on this line: import type { Options } from "@wdio/types"; //located in wdio.conf.t ...

"Encountering an unexpected error when Dockerizing an Angular App on Win10 Professional: EXPAND-ARCHIVE instruction not

I need to create a docker image for an Angular web application and deploy it on a Windows machine. However, I'm running into an issue when executing the command: docker build -t node . The following exception is thrown: Error response from daemon: ...

Exploring the hidden gems of npm package.json: the keys

There are some keys in the package.json file of Angular 2/4's source code that remain undocumented: { "name": "@angular/platform-browser/animations", "typings": "../animations.d.ts", "main": "../bundles/platform-browser-animations.umd.js", "m ...

Creating an NPM package using TypeScript for a JSPM application

I find myself facing a similar question to the one posed here: My NPM Package, typed-lexer, includes a d.ts file and its corresponding entries in the package.json file. When I consume this package in a regular node.js app using npm install and tsc --init, ...

Remove Fragment in Angular Routing after navigating to a different route

I am trying to figure out how to remove an Angular route fragment after I have already navigated to the Route+Fragment. Currently, the route fragment, which is part of the navigated URL, is causing an issue for users who have scrolled to a different sectio ...

The left side of the assignment expression is restricted from being a constant or a read-only property

Previously in TypeScript 1.x, everything was running smoothly with this line of code on my Express server: mongoose.Promise = global.Promise; (The syntax mongoose.Promise = global.Promise; is taken directly from the mongoose documentation) However, afte ...

Transmit information from child to parent as needed using @input and @output in Angular 2

Is there a way to pass an object from child to parent without relying on @viewChild or services? export class MultiSelectComponent implements OnInit { selectedItems: FormSelectComponentOption[] = []; @Input() items: FormSelectComponentOption[]; @Output ...

Solving automatically generated TypeScript MongoDB types for GraphQL results

Utilizing the typescript-mongodb plugin along with graphql-codegen to automatically generate Typescript types enables easy data retrieval from MongoDB and GraphQL output via Node. The initial input schema in GraphQL format appears as follows: type User @ ...

What is the best way to distinguish between tagged unions while narrowing down types using a type guard?

Exploring a Useful Helper Function const isKeyOf = <K extends PropertyKey, O extends object>(key: K, object: O): key is K & keyof O => key in object The isKeyOf function essentially narrows down the key type to determine if a key exists withi ...

Displaying tooltips with ngx-charts in Angular

Currently, I am working on developing a unique legend component that features individual material progress bars for each data entry. My goal is to display the pie chart tooltip when hovering over any of the entries within this custom legend. Below is a sn ...

How can we dynamically enable or disable a button based on the availability of input field data in an Angular FormGroup?

When it comes to deciding whether my form input field is required or not, I rely on the API data set. If the input is mandatory, I want to disable the button until the user inputs some value. As an absolute beginner in reactive form in angular, I could rea ...

Attempting to locate an element within the DOM using TypeScript

I am completely new to TypeScript. I have been attempting to locate an element using a selector, but no matter what I tried, the findElement() method always returns undefined. Can someone please point out where my mistake might be? Any assistance would b ...

Exploring Angular 9: A guide to targeting a specific field within ng-select using ngFor

Recently, I've been diving into Angular and JS. In my code, I have implemented 3 ng-select elements using a ngFor loop. <div class="filter-input" *ngFor="let input of data; let i = index"> <div class=&q ...

btn-group - The initial value of the btnRadio is set using an enum, preventing the button from being activated

Below is my btn-group setup: <div class="btn-group"> <label class="btn btn-primary" [(ngModel)]="type" btnRadio="{{myType.A}}" name="A" ngDefaultControl>A</label> <label class="btn btn-primary" [(ngModel)]="type" btnRadio= ...

Is it compatible to use Typescript version 2.4.2 with Ionic version 3.8.0?

Is it compatible to use Typescript 2.4.2 with Ionic 3.8.0? $ ionic info cli packages: (C:***\AppData\Roaming\npm\node_modules) @ionic/cli-utils : 1.18.0 ionic (Ionic CLI) : 3.18.0 global packages: cordova (Cordova CLI) : not insta ...

Creating a loading spinner that displays while waiting for a response from a service

Forgive me if this question seems basic, but I'm still new to the world of angular and observables are a mystery to me. I have some code where the options of the second select are dependent on the value selected in the first select. There's a me ...

How to Transmit Information from a Parent Component to a Child Component in Angular 2 When the Parent Component's Button is Clicked

Within parentComponenet.html </div><button(click)="discoverClicked()">Discover</button></div> <child-component></child-component> In parentComponent.ts file export class parentComponent implements OnInit { discove ...