How to remove an array from localStorage in Vue.js

Having an issue where, when I delete my array from localStorage, it seems to work fine. However, when I try to add a new option, the previous one reappears. I am currently using localStorage.removeItem('arrayOption'). Is there a way to permanently delete it? Thank you for any assistance.

<template>
   <div v-for="option in arrayOption" :key="option.id_option">
           
            <div>
                <div>
                    <p>{{ option.name}} </p>
                    <p>{{ option.description}}</p>
                </div>
                <div  >
                   
                        <button @click="deleteOption(option.id_option)">-</button>
                        <p v-if="option.count == 0">{{ count }}</p>
                        <p v-else>{{ option.count }}</p>
                       <button @click="addOption(option.id_option)">+</button>
                       </div>
                    </div>
                </div>
            </div>
</template>
new Vue({
  el: '#app',
  data() {
    return {
      arrayOption: [{
          id: 1,
          name: 'option1',
          description: 'I am option 1, add me to the cart'
        },
        {
          id: 2,
          name: 'option2',
          description: 'I am option 2, add me to the cart'
        },
        {
          id: 3,
          name: 'option3',
          description: 'I am option 3, add me to the cart'
        },
        {
          id: 4,
          name: 'option4',
          description: 'I am option 4, add me to the cart'
        }
      ],
      testCount: {},
    }
  },
   methods:{
    deleteOption(){
        localStorage.removeItem('arrayOption')
    },
     addOption(id){
        let addArrays = this.arrayOption[id]
        localStorage.setItem("arrayOption",JSON.stringify(addArrays))
    },
}

Answer №1

The problem lies in accessing an index from an array instead of retrieving the array item based on the selected id. It is recommended to make the following adjustment

updateOption(id){
  const selectedItem = this.optionsArray.find(item => item.id === id)
  localStorage.setItem("optionsArray",JSON.stringify(selectedItem))
}

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

Utilizing commas in JavaScript

Hi everyone, I'm having an issue with printing the message "Invalid password, Must Contain:". The problem I'm facing is that when I write the code in JavaScript, the comma is being interpreted as an operator instead of a regular English comma. Th ...

Retrieve the access ID from the conn.query result

When I run a SQL query, I need to extract the primary key (id) of the event returned so I can use it in another SQL query. However, attempting to access it using result.insertId returns null for the event object. Even logging result.insertId only outputs ...

Mapping data visually

Currently, I am in the midst of a vuejs project where I aim to create data visualizations on a map. My goal is to showcase a world map with percentages representing each country. However, I find myself at a loss on how to begin this task. Are there any r ...

In Typescript with Vue.JS, the type 'Users[]' does not include the essential properties of type 'ArrayConstructor' such as isArray, prototype, from, of, and [Symbol.species]

Embarking on my journey with typescript and vuejs, I stumbled upon a perplexing error that has halted my progress for the past 48 hours. The error message reads as: Type 'Users[]' is missing the following properties from type 'ArrayConstruct ...

Collaborative Vue component: Clients need to manually import the CSS

I recently created a Vue component using TypeScript that resulted in a separate CSS file being generated after the build process. However, I noticed that when the client imports this component, the CSS file is not imported automatically and needs to be exp ...

JavaScript: Dynamically load a script when a particular <a> element is in an active state

<script> function DisplayTag(){ var q1=document.getElementById( 'ctl00_ContentPlaceHolder1_ctl00_ctl00_Showcase' ).childNodes[1].innerHTML; var counter1=0; function executeScript(q1,counter1){ q1= document.getElementById( 'ctl00_Co ...

Error in Module Building: The path argument must be a string type. A different type was received, which caused the build to fail

I recently updated my Vuetify version from 1.5 to the latest 2.3.10. However, when trying to run the webpack server, I encountered this error message. Even after adding yarn add sass -D, the issue persists. Can someone please assist me in resolving this pr ...

The curly braces in AngularJS are failing to display the values on the HTML page

After trying various articles and solutions to different questions, I am still unable to resolve my issue. I am working on a blank ionic project and it is running smoothly in my browser using ionic serve without any errors. However, instead of displaying ...

The conundrum of nested function wrapping in Typescript and its impact on

Upon calling the following function, it returns a Promise<boolean>: const fnc = (i:number) : Promise<boolean> => Promise.resolve(true) // Promise<boolean> const res1 = errorHandler(errorPredicates.sdkError1, fnc, null, 4); However, ...

Oops! The react-social-media-embed encountered a TypeError because it tried to extend a value that is either undefined, not a

I recently attempted to incorporate the "react-social-media-embed" package into my Next.js project using TypeScript. Here's what I did: npm i react-social-media-embed Here is a snippet from my page.tsx: import { InstagramEmbed } from 'react-soc ...

How can I adjust the Line Opacity settings in Google Charts?

Within my Google Charts project, I have successfully implemented a feature that changes the color of a line halfway through a graph based on certain conditions using a dataView. Here is the code snippet demonstrating this functionality: var dataView = new ...

how to set a boolean value to true in a vue @click event?

@click.native="scrollTo(index,true)" My expectation: Always pass Boolean:true into the scrollTo function. Vue's reaction: Vue interprets true as a variable name, resulting in Number:index and undefined instead. Solution: ...

Error: The property 'rows' cannot be read because it is undefined

While working through the steps outlined in Getting started with Postgres in your React app, specifically when processing and exporting the getMerchants, createMerchant, and deleteMerchant functions, I encountered an error that says: "TypeError: Cannot rea ...

Trouble arises when attempting to create a two-column layout using Material UI's <Grid> component

My goal is to create a two-column layout where each column takes up half of the screen and has equal height. To better illustrate, take a look at this image. The code I've tried so far is not working as expected: import React from "react"; import { ...

Stop users from saving the page in Next.js

I'm currently working on a NextJs project that involves building an editor application. I want to ensure that the editor functionality does not work when users attempt to save the page in a different format, similar to how applications like Youtube an ...

Angular 2 ngFor generates a collection of rows and columns forming a single large column

It seems that ngfor is generating divs one by one, resulting in a poor design where they are stacked on top of each other. I would like to achieve a layout like this: [1] [2] [3] [4] [5] [6] However, the current outcome looks like this: [ 1 ] [ 2 ] [ 3 ...

Issue with timestamp in the Instagram API call to retrieve media using AJAX (GET /media/search)

My API call is returning a 400 bad request error message: {"meta":{"error_type":"APIInvalidParametersError","code":400,"error_message":"invalid parameters-check the max\/min-timestamps, if you supplied them"}} Even though my request appears to be co ...

Complex search queries in Mongodb using Mongoose

Is there a way to create a dynamic search bar that provides suggestions based on user input? For example, as a user types "j", they see options like "Java, JavaScript, JQuery", and when they add "a", they only see "Java, JavaScript". Here is the structure ...

Issue with triggering a modal while simultaneously closing another one

Let's consider this situation. I currently have a modal called Modal A, which has 2 buttons in the footer: Save and Close. When I click on the "Save" button, my intention is to close Modal A and open Modal B. The code that achieves this functionality ...

Django does not support running JavaScript natively

Wondering how to incorporate JavaScript into Django for creating chained forms? My first step was simply trying to understand how to run JavaScript. I've placed a basic main.js file in the static folder. I included a link to main.js in the header of ...