Is there a way to modify localStorage without having to refresh the page?

I'm currently working on a shopping cart that pulls products from a json-server. So far, I've successfully displayed the products, added the functionality to add items to the cart, and show the quantity. However, I'm facing a roadblock with the increment and decrement functions. The goal is for the product.count property to change whenever the user clicks on the + and - buttons (which is used to display in the cart table). Below is my code:

load cart from localstorage
function loadCart() {
    let products = JSON.parse(localStorage.getItem('products'));
    let cartTotalItem = document.querySelector('.cart__value');
    cartTotalItem.textContent = products.length;
    products.forEach(product => {
        let cartItem = document.createElement('tr');
        cartItem.innerHTML = `<td><img src="${product.imgSrc}" alt='product image'></td>
                  <td>${product.name}</td>
                  <td><span class='cart-price'>${product.price},000vnd</span></td>
                  <td>
                    <button action="remove" onclick='decrease()'>-</button>
                    <input name='product' class="product__quantity" type="number" min='1' max='100' value='${product.count}'>
                    <button action="add" onclick='change()' >+</button>
                  </td>
                  <td><span class='cart-total-value'>${parseInt(product.price) * product.count},000vnd</span></td>
                  <td>
                    <button class="delete--item"><i class="far fa-trash-alt"></i></button>
                  </td>`;
        tableBody.appendChild(cartItem);
    });
}

My approach to implementing the function:


function change() {
    let products = JSON.parse(localStorage.getItem('products'));
    for (let i = 0; i < products.length; i++) {
        let inputValue = document.querySelector('.product__quantity').textContent
        inputValue = products[i].count++
        localStorage.setItem('products', JSON.stringify(products))
    }
}

function decrease() {
    let products = JSON.parse(localStorage.getItem('products'));
    for (let i = 0; i < products.length; i++) {
        let inputValue = document.querySelector('.product__quantity').value
        inputValue = products[i].count--
        localStorage.setItem('products', JSON.stringify(products))
    }
}

The issue I'm facing is that I have to refresh the page for the changes to be reflected. Any help would be greatly appreciated.

Answer №1

It seems like you may need to reload the shopping cart by calling loadCart() again after making any changes to the products stored in localStorage.

function updateQuantityIncrease() {
    let products = JSON.parse(localStorage.getItem('products'));
    for (let i = 0; i < products.length; i++) {
        let inputValue = document.querySelector('.product__quantity').textContent;
        inputValue = products[i].count++;
        localStorage.setItem('products', JSON.stringify(products));
    }
    loadCart();
}

function updateQuantityDecrease() {
    let products = JSON.parse(localStorage.getItem('products'));
    for (let i = 0; i < products.length; i++) {
        let inputValue = document.querySelector('.product__quantity').value;
        inputValue = products[i].count--;
        localStorage.setItem('products', JSON.stringify(products));
    }
    loadCart();
}

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

Stuck on changing the background color of a DIV in WooCommerce product descriptions with CSS

I seem to be stuck on a simple fix and despite searching everywhere, I can't seem to make it work. The problem lies within WooCommerce on my WordPress site, where I suspect that my CSS is conflicting with WC's and causing some color problems. Yo ...

Maintaining the relative position of an SVG while scaling within a div element

I am in the process of incorporating my custom SVG knob icons into an electron application using flexbox. The challenge lies in keeping them centered within the rectangle icon regardless of browser size, as shown here. Ideally, the icons should adjust thei ...

Determining the presence of an array key

I have retrieved a multidimensional array from json_decode(). The JSON data is generated dynamically, resulting in random presence of certain keys. To prevent receiving an Undefined index: notice, I wrapped the array calls inside a function like this: fu ...

Developing Custom WordPress Plugins with AJAX POST/RETURN Requests

Currently, I am immersed in the development of a Custom WordPress Plugin that necessitates the implementation of AJAX to retrieve data without triggering a page reload. After consulting several tutorials, I have settled on the following basic plugin code. ...

My goal is to change the color of the input buttons from grey to black

I need help creating a webpage without JavaScript. Everything looks perfect except for the gray input/submit boxes. I've tried various options with code for buttons, but I can't seem to change the color to black, blue, or transparent. Is it even ...

Validating forms using TypeScript in a Vue.js application with the Vuetify

Currently, I am attempting to utilize Vue.js in conjunction with TypeScript. My goal is to create a basic form with some validation but I keep encountering errors within Visual Studio Code. The initial errors stem from my validate function: validate(): v ...

A method for reversing specific characters within lengthy strings

I'm currently tackling a coding problem: For a given string s and an integer k, the task is to reverse the first k characters for every 2k characters starting from the beginning of the string. If there are less than k characters remaining, reverse al ...

Using Three.js to extract Vertex Colors based on the z-coordinate of Vectors

Here is a sample: http://jsfiddle.net/c3shonu7/1/ The code demonstrates the creation of a BufferGeometry object by cloning an IcosahedronBufferGeometry's vertices. The goal is to apply a color gradient to the subdivided icosahedron, with lighter shad ...

Tips on accessing files saved in a one-to-many connection using Mongoose

I have multiple Schemas set up for Shops and Products. Each shop can have a variety of products, and I currently have 5 different shops with their own unique product listings. While I am able to save the products and find their corresponding IDs within eac ...

Include features once JSON has been loaded

Received this JSON data: { "info": [ { "id": 999, "products": [ { "id": 1, }, { "id": 2, } ] } ] } Info -- products -----id Here is the factory code snippet: AppAngular.factory('model', ['$http', f ...

Updating class after refresh of ng-repeat in AngularJS/Javascript

I am currently using angularJs in conjunction with cordova. Within my ng-repeat loop, each item has an ng-click event that stores the value of the item in an array. Additionally, when I click on an item, it toggles a class on the corresponding div (using ...

issue with non-existent value in v-for loop when using functional template refs

Scenario I am currently developing a personalized filtering feature. This feature allows users to add n filters that are shown using a v-for loop in the template. Users have the ability to modify input values and remove filters as needed. Challenge Issue ...

Programming the action of unfolding one window while simultaneously closing all others

I am facing an issue where the foldout function is working perfectly, but I need the second function to run first in order to close all other elements. Unfortunately, I can't seem to figure out what the problem is. Any help would be greatly appreciate ...

The alignment of Bootstrap 4 cards is not coming together as expected

Good morning, I'm currently working on organizing my Bootstrap card elements into rows of 3 cards each. I want the cards to be uniform in height and width, with spacing between them. For instance, if I have 7 cards, I'd have 3 rows of three card ...

Next.JS - What is the reason behind data fetching occurring on both the server and client side?

When I call a regular fetch function in the index.js component and then log the response to the console, something unexpected happens. Despite the fetch being inside the component function, the response is also logged on the server side: it shows up in the ...

Unreliable static URLs with Next.js static site generation

I've recently built a Next.js website with the following structure: - pages - articles - [slug].js - index.js - components - nav.js Within nav.js, I have set up routing for all links using next/link, including in pages/articles/[slug].j ...

Fusioncharts are unable to display any data due to an error

I utilized AJAX to dynamically render the chart. There are two main files involved: index.php and selectchart.php. The index.php file contains the AJAX code to render the chart. <div class="chart-area"> <div id="chart-1"><!-- Fusion Cha ...

Passing data received from a node.js request (using https.get) to a separate JavaScript file

I'm new to posting here, so my explanation might not be very clear. I am working on a project using node.js to fetch data and pass it to another js file for use in an html file. The structure of my app folder is as follows: -App -node_modules -publi ...

What measures can I take to ensure a function is only executed once, even in cases where multiple change events are triggered simultaneously?

Individual checkbox clicks work smoothly without any issues. However, checking all checkboxes at once may cause problems when dealing with a large number of municipalities to loop through, leading to flickering in the dropdown and preventing users from sel ...

When using axios to perform a post operation, the Firestore Cloud Function sends back an undefined response to the

Hello there, I am currently facing an issue with processing payments using Firestore Cloud Function and a payment Gateway named Yoco. The payment code seems to be functioning correctly as it is returning either a success or failure object. However, the p ...