refresh the localstorage array using vanilla JavaScript

I am attempting to remove an element from an array stored in local storage. I am using vanilla JavaScript within a Vue.js 3 component. Here is my array:

["96", "281", "287", "415", "650", "661", "378", "295"]

When I click on my trash icon:

https://i.stack.imgur.com/s0nsh.png

I have a function to delete the selected row:

const removeItem = (event) => {
        let itemId = event.target.parentElement.parentElement.children[0].id;
        console.log(itemId)

        // Saving IDs in LocalStorage to send to controller in next steps.
        // First, delete all content from LocalStorage.
        const existingEntries = JSON.parse(localStorage.getItem("items_ids"));
        existingEntries.splice(itemId, 1);
        localStorage.setItem("items_ids", JSON.stringify(existingEntries))

        addItemCart.value = addItemCart.value.filter(item => item.id != itemId);
    }

I need to update my array in localStorage. With this code, it does not delete the index and does not update my data.

Thank you for reading and apologies for my poor English.

Update:

With the accepted response, I was able to modify my code so that it runs smoothly and looks much cleaner:

const removeItem = (event) => {
        let itemId = event.target.parentElement.parentElement.children[0].id;

        // Saving IDs in LocalStorage to send to controller in next steps.
        // First, delete all content from LocalStorage.
        addItemCart.value = addItemCart.value.filter((item) => item.id !== itemId);
        let newArrayIds = []
        addItemCart.value.forEach(element => {
            newArrayIds.push(element.id)
        });
        localStorage.setItem("items_ids", JSON.stringify(newArrayIds));
    }

With this code, my table and localStorage are updated correctly.

Answer №1

It appears that the issue at hand is Vue not actively monitoring changes in your localStorage, resulting in a lack of updates. To ensure that Vue acknowledges any modifications to your localStorage, you must explicitly notify it when changes occur. For example:

...
  data() {
    return {
      yourList: []
    }
  }
...
 methods: {
    removeItem (clickedId) {
      this.yourList = this.yourList.filter((item) => item.id !== clickedId);
      localStorage.setItem("items_ids", JSON.stringify(this.yourList));
    }
  },

This code snippet demonstrates our approach of managing reactivity within the localStroage by focusing on the yourList data and updating localStorage manually.

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

Apexcharts - Blank space in area chart

I am currently facing an issue while trying to create an area chart using apexcharts on nuxt (vue2). The problem is that the area is not being filled as expected, and the options I have set in chartOptions for fill are affecting the line itself instead of ...

After reaching a total of 20 entries, req.body will automatically convert the array into an

I have the ability to dynamically add properties to my form: <form action=""> <div class="property"> <label>Name : <input type="text" name="properties[1][name]"></label> <label>Order : <input type="text" na ...

Observer fails to activate

I am currently working with Vue 3 using the options API. In the code below, I have a watch object monitoring changes to isToggleBtnLabelDigitizePolygon. When the method onDigitizePolygon changes the value of isToggleBtnLabelDigitizePolygon, the computed p ...

The Fetch API's Post functionality is currently experiencing issues

fetch('http://localhost:9000/api/app/contact', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ email: this.state.email, contactNumber: ...

Sorry, we couldn't locate the API route you are looking for

Within my Next.js project resides the file main/app/api/worker-callback/route.ts: import { NextApiResponse } from "next"; import { NextResponse } from "next/server"; type ResponseData = { error?: string }; export async function PO ...

Utilizing VueJs (Quasar) to access vuex store within the router

Recently, I have been diving into learning Vuex and creating an authentication module. Following a tutorial, I reached a point where I needed to use the store in the router. However, after importing my store at the top of the router index.js file, I notice ...

Ways to assign scores to every response button

Below is an excerpt of code that showcases a list of potential answers for each question in the form of checkbox buttons. The task at hand is to assign marks to each answer button, which can be retrieved from the database. Marks for correct answers are obt ...

Validator returns undefined when expressing invalid data

Having an issue with validation, here is the code snippet: routes.js var express = require('express'); var router = express.Router(); var hello_controller = require('../api/controllers/helloController'); var { validationRules, validat ...

Find all the different ways that substrings can be combined in an array

If I have a string input such as "auto encoder" and an array of strings const arr = ['autoencoder', 'auto-encoder', 'autoencoder'] I am looking to find a way for the input string to match with all three values in the array. ...

Troubleshooting Issues with Google Analytics Internal Link trackEvent Functionality

Using ga.js, I have encountered an issue with tracking internal links on my website. Despite successfully tracking external links and viewing real-time reports for events, the internal links are not being recorded accurately. While testing pages, the tot ...

Utilizing v-model in Laravel: A Step-by-Step Guide

Is it necessary to import anything in the app.js file or download something via npm when using v-model instead of v-modal in my app.js file, after running npm install? My template and all other Vue functionality seem to be working perfec ...

Datepicker malfunction in Django's administrative interface

Currently, I am attempting to filter results by dates using daterangefilter. However, I am experiencing issues with my datepicker functionality. Although the icon appears, the datepicker itself is not functioning as expected. In an effort to troubleshoot ...

Is it possible to set data using a React Hooks' setter before the component is rendered?

Instead of making a real API call, I am exporting a JS object named Products to this file to use as mock data during the development and testing phase. My goal is to assign the state of the function to this object, but modified with mapping. The current st ...

Master the art of returning two functions within a single function in Javascript with NodeJS and ExpressJS

Currently, I am facing an issue where I need to combine two objects and return them in one function. The challenge lies in the fact that both objects have almost identical properties, but different values. To tackle this problem, I created two separate fu ...

What is the method for triggering the output of a function's value with specified parameters by clicking in an HTML

I am struggling to display a random number output below a button when it is clicked using a function. <!DOCTYPE html> <html> <body> <form> <input type="button" value="Click me" onclick="genRand()"> </form> <scri ...

A scheduled task in Node.js set to run every day at 2 AM

My nodejs cron currently runs every 5 hours using the code below: cron.schedule("0 0 */5 * * *") How can I modify it to run daily at 2 AM instead? Thank you ...

Execute HTML code within a text field

Is it possible to run html code with javascript inside a text box, similar to w3schools.com? I am working solely with html and javascript. Thank you. For example, I have two text areas - one for inserting html, clicking a button to run the code, and displ ...

Tips for customizing vue-bootstrap-datetimepicker: Adjusting width and adding icons for a personalized touch

I am working with two date pickers from the Vue Bootstrap DateTimePicker package. While the functionality is great, I need to modify their appearance. Here is the relevant code snippet: <template> <div> <div class="form-row"> ...

Utilizing Jquery tabs for consistent height display

Currently, I am utilizing jquery tabs for showcasing various content. This is what my functions look like: $(function() { $( "#tabs" ).tabs(); }); I attempted to ensure all tabs have the same height by using this approach: var heightStyle = ...

Placing options and a clickable element within a collapsible navigation bar

Within my angular project, there are 4 input fields where users need to enter information, along with a button labeled Set All which will populate them. https://i.sstatic.net/1GGh1.png I am wondering how I can organize these input fields and the button i ...