Store the response data in LocalStorage items

I have a question regarding handling responses in localStorage. When someone visits URLs like /products/1 or /products/2, the frontend automatically sends the corresponding id (1 or 2) to the server. The server then responds with data for that particular id. My goal is to store this response in localStorage, but I'm facing an issue. Every time a new URL is visited, such as /products/2, the previous data in localStorage gets replaced instead of being added to it. How can I ensure that new data is continuously added to localStorage without overriding the existing value?


fetch("/apps/proxy/sendid", {
        method: "POST",
        headers: {'Content-Type': 'application/json'}, 
        body: JSON.stringify(jspid)
      }).then(function (response) {
        // The API call was successful!
        console.log(response);
        return response.json();
      }).then(function (data) {
        // This is the JSON from our response
        console.log(data);

        const productsDetails = JSON.parse(localStorage.getItem('future')) || [];

        productsDetails.push(data);
        
        localStorage.setItem('future', JSON.stringify(productsDetails));

      }).catch(function (err) {
        // There was an error
        console.warn('Something went wrong.', err);
      });
  }

Answer №1

Begin by retrieving the existing items from localStorage and storing them in the variable productsDetails. Add the new items to this array.

let productsDetails = localStorage.getItem('upcoming');

if(null === productsDetails) {
    productsDetails = [];
}

productsDetails.push(newData);

localStorage.setItem('upcoming', JSON.stringify(productsDetails));

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

Troubleshooting: Inconsistencies with AngularJS' ngmaxlength and ng-required

Input Type <div class="form-group" ng-class="{ 'has-error': loginForm.password.$dirty && loginForm.password.$error.required }"> <label for="password">{{ 'PASSWORD' | translate }} <span class="required-field"& ...

Can an array in Java be created without specifying the number of elements?

I'm encountering an issue while working with arrays in Java. When I declare a character array like this, my program throws an "out of bound array" exception: char[] ipx = {}; for( int i =0; i <= 63 ; i++ ){ ipx[i] = myString.charAt(i); } I don&ap ...

Detecting the presence of a file on a local PC using JavaScript

In the process of creating a Django web application, I am exploring methods to determine if a particular application is installed on the user's local machine. One idea I have considered is checking for the existence of a specific folder, such as C:&bs ...

Remove information inside table cells <td> when the table is in edit mode by using JavaScript or jQuery

I am facing an issue where I need to clear the data in a HTML td onfocus, especially in an editable table using JQuery tabledit. The table is populated with data from a database and I want to be able to edit a td without having to manually delete the exist ...

What is the best way to display the text of a button once it has been clicked?

Trying to implement a fade-in effect on text when clicking a button. Any assistance would be greatly appreciated! $(".btnClick").click(function(event) { var x = $(this).text(); if (x == "PowerApps") { $(this).parent(".show-details").find('. ...

All of the jstree add-ons are not working as expected

I've encountered a frustrating issue that I can't seem to find any documentation on. While I'm still relatively new to jQuery, my understanding is growing, but I'm completely unfamiliar with the jsTree plugin. The problem I'm faci ...

The PopupControlExtender in ajaxToolkit seems to be malfunctioning when used with a textbox that has Tinymce

I recently built a website using ASP.NET, and I have a feature where a small tooltip appears on the right side of a text box when the user focuses on it. To achieve this, I am using the ajaxToolkit:PopupControlExtender in my code. <asp:TextBox ...

What are the implications of utilizing a query string in a POST request?

In our system, POST requests are sent from the frontend to the backend. Instead of using the body to pass data to the server, these requests utilize query strings in the URL params. It is important to note that these requests only contain string parameter ...

Maintain consistent spacing after receiving a value

I have a content editable span where you can write whatever you want. For example: Hello, My name is Ari. However, when I try to retrieve the text and alert it using my program, it displays without any line breaks or spacing like this: "Hello,My name is ...

What is the most effective method for implementing multiple textures in three.js?

After recently transitioning to three.js as my renderer, I am eager to establish a texture mapping system. However, determining the best practice for this task is a bit uncertain for me. Here is the scenario I am dealing with: My levels consist of numero ...

How to access event.target in Internet Explorer 8 with unobtrusive Javascript

Here is a function that retrieves the target element from a dropdown menu: function getTarget(evt){ var targetElement = null; //if it is a standard browser if (typeof evt.target != 'undefined'){ targetElement = evt.target; } //otherwise ...

Keypress Lagging woes: Latest Meteor Update

While I am updating a MongoDB model immediately upon keypress, it seems to lag behind due to the value being attached to that model. What would be the most effective way to update the model both on keypress and when refreshing the page so that the input re ...

Node.js and react-create-app are not compatible with each other

I am currently using node.js version 14.6.0 and node-v version 7.20.0 To replicate the issue, follow these steps: npx create-react-app my-app2 Once everything is installed, run npm i After completing the above steps, you may encounter the following warn ...

Emulate sequelize using Jest in combination with sequelize-mock

In my latest project, I have been implementing TDD as the primary methodology along with integration tests. One of the tasks at hand is to retrieve all users from the database. //controller.js const UserService = require('../services/user'); mod ...

Retrieving the value from a concealed checkbox

I have been searching everywhere, but I can't seem to find a solution to this particular issue. There is a hidden checkbox in my field that serves as an identifier for the type of item added dynamically. Here's how I've set it up: <inpu ...

Changing the way Hook setState is used with arrays in React by leveraging Splice

Can anyone help me figure out why my array splice functionality is removing all items below the clicked item instead of just that one item? I tried creating a copy of the array to modify, but it's not working as expected. Any suggestions? export defau ...

Generate Select dropdown menus and set their values dynamically

Within the angular app.js file, I am dynamically populating a form with multiple select boxes, each having a unique id. How can I retrieve the selected values from these select boxes within the controller? A variable has been added: $scope.sibling_type = ...

Error Detected: the C# script is not compatible with Javascript and is causing

I am facing an issue where I can successfully send information from the database, but I am unable to load the table on the page. When I check the data received with an alert, it appears to be in JSON format, but it still displays the wrong image on the web ...

Utilize an iframe input field to initiate a Jquery event

Thanks to this amazing platform, I was able to discover a solution for expanding an iframe upon clicking using HTML and Jquery. However, my issue remains unresolved. I have successfully expanded the iframe with text, but I want to use input fields within ...

Using JSON.parse in Node.js to manipulate arrays with Javascript

While taking an online course, I came across a confusing code snippet: notes = JSON.parse(notesString). The confusion arises from the fact that this code is supposed to result in an object, but it's being treated as an array. Isn't JSON.parse sup ...