Dealing with a missing item in local storage in an Angular application

When working with local storage, I have a function that saves certain values and another method that reloads these values. However, what is the best approach to handle missing items in the local storage? This could happen if a user deletes an item or if it simply doesn't exist. The methods for getting and setting the local storage coordinates are as follows:

    get savedValues(): { val1: number, val2: number, val3: number }[] {
        if (localStorage.getItem('savedValues') === null) {
            console.log("null");
            return null;
        }
        return JSON.parse(localStorage.getItem('savedValues'));
    }

    set savedValues(value: { val1: number, val2: number, val3: number }[]) {
        localStorage.setItem('savedValues', JSON.stringify(value));
    }

This next method demonstrates how the coordinates are reloaded from the local storage:

    reload(): void {
        try {
            for (var i = 0; i < this.savedValues.length; i++) {
                this.oldValues[i].val1 = this.savedValues[i].val1;
                this.oldValues[i].val2 = this.savedValues[i].val2;
                this.oldValues[i].val3 = this.savedValues[i].val3;

            }
        }
        catch (Exception) {
            console.log("savedValuesitem is null in the local storage");
        }
    }

What is the correct way to try catching exceptions related to null fields in the local storage? I have also attempted:

if (this.savedValues !== null) {...}

However, this approach seems to be inefficient when checking the local storage.

Answer №1

Make sure to verify the value of an undefined:

if (this.savedCoordinates !== null) {
...
}

Answer №2

Instead of using a try/catch block in this situation, I would recommend implementing a simple null-check approach. This is because not finding a value in the local storage is expected behavior rather than an error:

reload(): void {
    if (this.savedCoordinates !== null) {
        for (var i = 0; i < this.savedCoordinates.length; i++) {
            this.nodes[i].x = this.savedCoordinates[i].x;
            this.nodes[i].y = this.savedCoordinates[i].y;
        }
        return;
    }

    console.log("savedCoordinates item is null in the local storage");
    return;
}

Answer №3

It's important to only check the localStorage once:

    verifyStorage(): void {
   
        let storedCoords = this.retrieveCoordinates;
        if (storedCoords == null) {
         ...
        }
        else{
         for (var i = 0; i < storedCoords; i++) {
            this.points[i].x = storedCoords[i].x;
            this.points[i].y = storedCoords[i].y;
           }
         }
   
   }

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

Ways to obtain the present value in Angular

Hello, I am looking for assistance in displaying Toast notifications on my View whenever the number of notifications increases (i.e., when new data is added to the database). I have attempted to use this function, but I am unsure how to retrieve the curre ...

What is the best way to display individual records from a Web API on the user interface?

Just a heads up: I'm unable to utilize pagination (skip, take) due to the data being sourced from multiple tables. For more information, you can refer to the Report model. I attempted to retrieve the data individually on the UI through WebAPI. The ...

Steps for exporting various elements from a .vue file

In my Vue project, I am incorporating TypeScript along with Vue. There is a specific scenario where I need to export multiple items from my .vue file. Here's an example of what I want to achieve: // FooBar.vue <template> ... </template& ...

Utilize Array.push to add 2 new rows to a table using Angular 4

I have two arrays that are almost identical, except for two items which are the fakeDates: this.prodotti.push({ idAgreement: this.idAgreement,landingStatus: this.landingStatus, landingType: this.landingType, startDate: this.startDate, expirationDate: thi ...

Using TypeORM with a timestamp type column set to default null can lead to an endless loop of migrations being

In my NestJs project using TypeORM, I have the following column definition in an entity: @CreateDateColumn({ nullable: true, type: 'timestamp', default: () => 'NULL', }) public succeededAt?: Date; A migration is gene ...

Encountering an "ionic 4 frame-ancestors *" error while attempting to watch a Twitter video

Currently, I am in the process of developing a news app using Ionic 4. I recently tackled the challenge of embedding tweets in Twitter cards successfully. However, a new issue has arisen. When a tweet includes a Youtube video, everything works perfectly ac ...

button listener event

Is there a way to verify if a button has been selected? <ul> <li *ngFor="let p of arrray; let i = index" > <button class="btn btn-success" (click)="onLoveIt(i)" >Love it!</button> &nbsp; </li> </ul> ...

Setting up `ng serve` to detect changes in a containerized Angular 2 application

Currently, I am 'dockerizing' an existing Angular 2 application that is being run on angular-cli version 1.0.0-beta.31. I am facing difficulties in configuring ng serve to automatically reload my app whenever a file in the working directory is u ...

Is there a program available that can efficiently convert or translate JSON objects into TypeScript types or interfaces?

Can anyone recommend a tool that can easily convert a JSON object into a TypeScript type or interface? An example input would be something like this: I'm hoping to paste the JSON object into the tool and receive an output structure similar to: expor ...

Next.JS-13 has encountered an inappropriate middleware in its App Based Routing functionality

I am currently working on developing a user authentication system that includes features for Login, Signup, and Logout. As part of this project, I have created a middleware.ts file in the src directory, which is located next to the app directory. Below is ...

Utilizing the MapToIterable Angular Pipe with TypeScript

Exploring the implementation of a pipe in Angular. Discovered that ngFor doesn't work with maps, prompting further research to find a solution. It seems that future features may address this issue, but for now, utilizing a mapToIterable pipe is the re ...

Angular - The parameter type '(error: any) => void' cannot be assigned to the type '() => void'

I encountered an issue with my error handling code in Angular-11: return this.api.post('auth/user/login', data, headers).subscribe( (result: any) => { console.log(result.message); console.log(result.code); if ...

`Is there a way to maintain my AWS Amplify login credentials while executing Cypress tests?`

At the moment, I am using a beforeEach() function to log Cypress in before each test. However, this setup is causing some delays. Is there a way for me to keep the user logged in between tests? My main objective is to navigate through all the pages as the ...

Issue with a child element that is malfunctioning because of the parent element

There seems to be an issue with the child tag link not working because of the parent tag link. Is there a solution for this problem? Please provide suggestions. Here is the code snippet: <div class="d-flex flex-wrap mx-auto mb-4"> < ...

Is it possible to modify the HTML/CSS of a child component using the parent component in Angular 2+?

Is there a way to dynamically add text and style to a specific row in a child component based on the parent's logic? (parent): <body> <child-component></child-component> </body> (child): <div *ngfor = "let record in r ...

event activated when the input file is prepared for utilization by the browser

Which event should be used in conjunction with <input type="file"> to receive notification when the browser is ready to use the selected file? Once the user clicks on <input type="file"> and selects a file, I want to utilize that file within t ...

How can you identify changes in localstorage and then trigger the activation of a new boot file or reallocate a value using Vue.js or JavaScript?

When users log in, they have the option to choose from 3 domains: dev, demo, and sandbox. The configuration for these domains is set in the Boot.js file using Axios. The boot file is triggered prior to the firing of the Vue instance. Below is the content o ...

Is it possible to upload an image-containing object to Mongodb with the help of Node.js?

I am struggling to upload an object containing an image to the mongodb database using Node.js. Angular File onSelectedFile(event){ this.edit_image = event.target.files[0]; } editProfile(e){ const user={ email:this.edit_email, img:this.edit_imag ...

Building and executing an Angular 2 program on the Windows platform: Step-by-step guide

After successfully installing npm and related packages including TypeScript and Angular 2, I am encountering difficulties running Angular 2 in my browser on a Windows platform. Can someone provide a step-by-step guide to help me create and run Angular 2 ...

How to Share Angular Modules Between Two Projects with Ivy Compilation Necessity

Query: I am faced with the challenge of sharing common modules between two Angular projects, one of which requires full Ivy compilation to function properly. To manage these shared resources, we have set up a private GitHub NPM repository. However, becaus ...