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

A pattern matching algorithm that verifies a series of port numbers (ranging from 1 to 65535) spread out across

I am in search of a regular expression that can accurately identify valid port numbers (ranging from 1 to 65535) within a text area. The input format will resemble the following: 80 80 25 53 110 --- --- This pattern will continue across multiple lines, wi ...

Creating a delayed queue using RxJS Observables can provide a powerful and

Imagine we have a line of true or false statements (we're not using a complicated data structure because we only want to store the order). Statements can be added to the line at any time and pace. An observer will remove items from this line and make ...

Addressing command problems in Angular

I am experiencing an issue with a dropdown functionality. When a user selects an option and then presses either the "Delete" or "Backspace" button on the keyboard, the value from the dropdown clears which is working correctly. However, I am attempting to i ...

Is there a way to display the number of search results in the CodeMirror editor?

After conducting some research on how to integrate the search result count in Codemirror like the provided image, I was unable to find any solutions. I am currently working with Angular and utilizing ngx-codemirror, which led me to realize that editing the ...

What is a more effective approach for managing form data with React's useState hook?

Seeking a more efficient solution to eliminate redundancy in my code. Currently, I am utilizing useState() for managing user data, which results in repetition due to numerous fields. Below is a snippet of my current code: const [lname, setLast] = useState& ...

Receiving a CORS issue while integrating Django as the backend for an Ionic application

I have integrated Django Rest Framework as a backend for my Ionic application. The API setup using JWT is successfully tested with Postman. However, when attempting to make an API call from the Ionic app, I encounter the following errors: Error 1 Cross-Or ...

How is it possible that TypeScript does not provide a warning when a function is called with a different number of arguments than what is expected?

I am working on a vanilla JavaScript project in VS Code and have set up jsconfig.json. Here is an example of the code I am using: /** * @param {(arg: string) => void} nestedFunction */ function myFunction(nestedFunction) { // Some logic here } myFu ...

Leveraging FormControlName in Typescript to Interact with HTML Components in Angular 4

How can I use FormControlName to access HTML elements in typescript? Typically, I am able to access HTML elements using their ID. For example: var element = document.getElementById("txtID") But is it possible to access the element without using its ID a ...

Is there a way to incorporate margins into a React component using TypeScript?

I am currently facing a challenge in passing CSS attributes to a component that I am working with. The reason behind this is that I need to modify the margins to fit a specific space, hence my attempt to directly pass the margins. Does anyone have any sug ...

What could be causing the issue where only one of my videos plays when hovered over using UseRef?

I'm currently working on a project where I have a row of thumbnails that are supposed to play a video when hovered over and stop when the mouse moves out of the thumbnail. However, I've encountered an issue where only the last thumbnail plays its ...

Implementing Angular 2 reactive forms checkbox validation in an Ionic application

I have implemented Angular Forms to create a basic form with fields for email, password, and a checkbox for Terms&Conditions in my Ionic application. Here is the HTML code: <form [formGroup]="registerForm" (ngSubmit)="register()" class="center"> ...

Error encountered: The combination of NextJS and Mongoose is causing a TypeError where it is unable to read properties of undefined, specifically when trying

Versions: Next.js 14.1 React 18 I am currently developing a profile section where users can update their profile information such as username, name, and profile photo. To achieve this, I have implemented a component that contains a form (using shadcn) to ...

Varieties of data classifications for the information obtained from supabase

1 I'm encountering an issue while attempting to define the data types from Supabase. I received an error message stating: "type '{ id: string; title: string; capacity: number | null; start_date: Date | null; start_time: string | null; end_ ...

What is the best way to destructure a blend of React props and my own custom props in my code?

I have a requirement to develop a custom React component that serves as a wrapper for the Route component in order to create secure routes. The challenge I am facing is how to access the element property, which is typically specified in the <Route> e ...

Styling Form validation with Ant Design

Can a className prop be included in the Form.Item validation? <Form.Item name="username" rules={[ { required: true, message: '...' }, className="customValidation" //<- attempting to add a className but it is not fu ...

Unlock the power of RouteReuseStrategy for select routes only by following these steps

Is it possible to apply the RouteReuseStrategy selectively to certain routes? What I mean is having a unique implementation of RouteReuseStrategy for each route with children, where the methods are only triggered when a route in a specific 'tree&apos ...

Issue with updating state in child component preventing addition to state

Recently, I made the switch to TypeScript in my NextJS project using Create T3 App. One of the components in my app involves updating the state after a Prisma mutation is performed. I attempted to pass the setItems (which was initialized with useState) to ...

What are the steps for utilizing the watch feature in Vue.js with TypeScript?

Currently, I am looking to convert this JavaScript script into TypeScript. However, I require the syntax for watchers. export default { props: ['branch_id'], watch: {} } ...

The type '{ domain: any; domainDispatch: React.Dispatch<any>; }' cannot be assigned to a type 'string'

Within my codebase, I am encountering an issue with a small file structured as follows: import React, { createContext, useContext, useReducer } from 'react' const initState = '' const DomainContext = createContext(initState) export co ...

Mockery Madness - Exploring the art of mocking a function post-testing a route

Before mocking the process function within the GatewayImpl class to return the 'mockData' payload, I need to ensure that all routes are tested. import payload from './payloads/payloadRequire'; // payload for request import {Gate ...