Update a value in the sessionStorage using Angular

I am working on a function that handles checkbox options based on event.target.name. The goal is to add the checkbox option to session storage if it's not already there, and update the value if it exists. However, I'm facing some issues with my code. Can you help me identify which part needs fixing?

saveSetting(event){
    const getSesssion = sessionStorage.getItem('setting');

    if(getSesssion) {
      const parseSession = JSON.parse(getSesssion);

      parseSession.forEach((item) => {
        if(item.setName === event.target.name) {
          this.changeValue = !this.changeValue;
          item.setValue = this.changeValue;
          parseSession.pipe(map(item => this.settingList.push({ setName: event.target.name, setValue: this.changeValue })));
          sessionStorage.setItem('setting', parseSession);
        }
      });
    } else {
      this.settingList.push({ setName: event.target.name, setValue: true });
      const parseList = JSON.stringify(this.settingList);
      sessionStorage.setItem('setting', parseList);
    }
  }

I need to update the value in session storage if it already exists.

Answer №1

You have limited control over the session storage as you can only set and delete data (editing is essentially a set operation). When it comes to the logic, the new object should only be added if it's not already in the existing list; otherwise, you'll need to edit the existing item. The code snippet below should function correctly. Please feel free to reach out if you encounter any problems.

  saveSetting(event){
        const getSesssion = sessionStorage.getItem('setting');
    
        if(getSesssion) {
          const parseSession = JSON.parse(getSesssion);
          let isSetValueExist : boolean = false;
          parseSession.forEach((item : any) => {
    
            if(item.setName === event.target.name) {
              isSetValueExist = true;
              this.changeValue = !this.changeValue;
              item.setName = event.target.name
              item.setValue = this.changeValue;
              sessionStorage.setItem('setting', parseSession);
            }
          });
          if(!isSetValueExist)
          {
                    parseSession.push({ setName: event.target.name, setValue: true });
                    const parseList = JSON.stringify(parseSession);
                    sessionStorage.setItem('setting', parseList);
          }
    
        } else {
          this.settingList.push({ setName: event.target.name, setValue: true });
          const parseList = JSON.stringify(this.settingList);
          sessionStorage.setItem('setting', parseList);
        }
    }

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

Functionality issue with Angular's custom form control (Mandatory)

Exploring custom form controls in Angular has been quite an adventure for me, especially when it comes to setting required fields within a mat-stepper. My current challenge involves creating a reusable address template where I've configured the requir ...

Transforming a JavaScript chained setter into TypeScript

I have been utilizing this idiom in JavaScript to facilitate the creation of chained setters. function bar() { let p = 0; function f() { } f.prop = function(d) { return !arguments.length ? p : (p = d, f); } return f; } ...

An error occurs when trying to use AWS.Comprehend as a constructor in the aws JavaScript SDK

I'm attempting to utilize the Amazon Comprehend API using the AWS JavaScript SDK. However, I keep encountering Uncaught (in promise): TypeError: undefined is not a constructor (evaluating 'new AWS.Comprehend... ' What am I doing incorr ...

Leveraging the Power of SASS Variables Across Your Entire NativeScript Application

Currently, I am in the process of developing an app using NativeScript 6.4.1 along with Angular 8. In order to enhance my styling capabilities, I have decided to incorporate SASS due to its advantageous features like variable names. My designer has suppli ...

Steps for deleting an image from a component in Angular before getting a new one from API

In my application, there is a child component responsible for fetching and displaying images from an API on the template. The parent component consists of a list of items, and when a user selects an item from the list, a request is made to the API to retri ...

Angular: Do Modules or Components Represent Pages in an Application?

Is it better to have a separate module for each page or a separate component for each page? What are the benefits of using one module for an entire site and loading different components for page transitions? ...

Creating dynamic DOM elements in Angular templates by utilizing variable values as element types

There's a component I'm working with that I want to render either as a div or span dynamically. To achieve this, I've created an input variable called elementType. Now, the challenge is how to properly render it in the template. Here's ...

The 'Component' binding element is assumed to have an unspecified 'any' type in TypeScript

Hello, I'm new to coding and encountering an issue with the code below. My goal is to create a protected "Dashboard" page, but I keep getting a binding error that says: Binding element 'Component' implicitly has an 'any' type.ts( ...

Allow web applications in Apache ServiceMix to communicate across different domains by enabling Cross

My current project involves deploying an angular2 webapp in servicemix as a war file. As a result, the app runs on the localhost:8181/angular2webapp URL. Additionally, I have a bundle installed for handling REST requests, which essentially functions as a c ...

Connect the names of the sheets with the data in the tables

I have a simple question: I want to connect specific sheet names in my workbook with a table that contains a range of dates. The sheet names should be something like "blablabla" + Table@1. Although I have attempted to design a solution, it doesn't se ...

Steps to dynamically populate dropdown menus based on the selected options from other dropdown menus

I am working on a project that involves two dropdown menus. The options for the first dropdown menu are stored in a file called constant.ts. Depending on the selection made in the first dropdown, the options for the second dropdown will change accordingly. ...

Having trouble installing npm package in Angular project

After cloning my project from GitLab, I encountered an issue while trying to install the NPM packages. When I ran npm install, an error popped up: https://i.stack.imgur.com/WNT5s.png Upon checking the log file, I found the following error message: 3060 ...

Arranging the output of a Typescript project

I'm currently advocating for Typescript to be implemented in our web application. Can anyone provide insight on the best method for structuring Javascript output files? Should they be excluded from source control? And when it comes to testing, is it p ...

Updating Angular 13 with charts.js and ng2-charts may expose unfixed vulnerabilities

I am facing an issue while updating chart.js and ng2-charts in Angular 13. After running npm i [email protected] and npm i [email protected], I encountered vulnerabilities that couldn't be resolved with npm audit fix. Do I need to update any ...

Encountering the following error message: "E11000 duplicate key error collection"

Currently, I am in the process of developing an ecommerce platform using the MERN stack combined with TypeScript. As part of this project, I am working on a feature that allows users to provide reviews for products. The goal is to limit each user to only o ...

The value of the signedIn variable in AWS Amplify is currently undefined

While utilizing the aws-amplify library from the provided website, I observed that the variable this.signedIn is not referenced anywhere on the linked page. My intention is to use it as a boolean indicator, determining whether the user is currently signed ...

Using POST parameters with HTTP Client in Angular 2

I have been working on converting my jQuery code into Angular2. While the jQuery code is functioning correctly, the Angular2 code seems to be producing a different output from the API. I have already compared the parameters and endpoint using firebug/cons ...

Difficulty in monitoring the present machine status through XState in a React application

I'm encountering an issue where I am trying to access the Machine state from within a function in a React component using state.value. However, the current state never changes and it always displays the initial state. Strangely, if I include an onClic ...

The function parameter in Angular's ngModelChange behaves differently than $event

How can I pass a different parameter to the $event in the function? <div class='col-sm'> <label class="col-3 col-form-label">Origen</label> <div class="col-4"> <select ...

Together, we have a shared Yarn JS directory for both the client and server components,

The scenario: both the client and server share a folder named shared when we make changes to the shared folder in our development process, we need the corresponding references to update in both the client and server the server seems to w ...