After refreshing the page, the data stored in the localStorage array gets replaced

After refreshing the webpage, my localStorage array values are being overwritten. During a session, I am able to update values on the front end, and the array in localStorage gets updated accordingly. However, if multiple inputs are changed during a session, adding more values to the array, when one input is edited after a refresh, all arrays in localStorage are deleted and replaced by the new session's input update. I've been trying to solve this issue for a while, but can't find a solution to ensure that after a refresh, all input values are stored in the existing array without being overwritten.

var presetsArr = [];

if (!localStorage.getItem("presetsArr") || localStorage.getItem("presetsArr").length < 0) {
  init();
} else {
  initIfLocalStorage();
}
function initIfLocalStorage () {
presetsArr = JSON.parse(localStorage.getItem('presetsArr'));

  for (var i = 0; i < presetsArr.length; i++) {
    if (presetsArr[i].freq) {
    osc.frequency.value = presetsArr[i].freq;
    freqSlider.value = presetsArr[i].freq;
    freqDisplay.innerHTML = freqSlider.value;
    }
    if (presetsArr[i].detune) {
    osc.detune.value = presetsArr[i].detune;
    detuneSlider.value = presetsArr[i].detune;
    detuneDisplay.innerHTML = detuneSlider.value;
    }
    if (presetsArr[i].gain) {
    volume.gain.value = presetsArr[i].gain;
    }
  }

freqSlider.addEventListener("click", function(e) {
    osc.frequency.value = this.value;
    freqDisplay.innerHTML = this.value;
    bookmark["freq"] = osc.frequency.value;
    presetsArr.push(bookmark);
    presetsArr = localStorage.setItem("presetsArr", JSON.stringify(presetsArr)) || [];
  })

  detuneSlider.addEventListener("click", function(e) {
    osc.detune.value = this.value;
    detune.innerHTML = this.value;
    bookmark["detune"] = osc.detune.value;
    presetsArr.push(bookmark);
    presetsArr = localStorage.setItem("presetsArr", JSON.stringify(presetsArr)) || [];
  })

To illustrate, in the first session, I updated both frequency and detune values which were successfully stored in the array. https://i.sstatic.net/qKN8A.jpg

However, in the second session after refreshing, when I changed the detune value again, the entire localStorage array was overwritten. The frequency key is now missing, leaving only the detune value. Consequently, the next time I try to play my oscillator after a refresh, no sound is produced because the frequency value in the array was removed.

https://i.sstatic.net/D5GG0.jpg

Answer №1

If you're facing a similar issue, here's the solution that worked for me.

Following Patrick Evans' advice, I realized my mistake of assigning .setItem() to a variable even though it doesn't return any value. To resolve this, I started creating a new empty array each time I clicked after refreshing in a new session. However, that wasn't enough. I encountered another problem where I was trying to push values into a non-existing array and getting a null error. To fix this, I updated my click handler to:

presetsArr = JSON.parse(localStorage.getItem('presetsArr')) || [];
    presetsArr.push(bookmark);
    localStorage.setItem("presetsArr", JSON.stringify(presetsArr));

The addition of || [] helped me eliminate the Null error. Even though I initially created an empty array at the beginning of my program, for some reason, I couldn't push values into it inside the click handler. This quick shortcut allowed me to check if there was an existing array to push to and create one if not before proceeding with the push operation.

Now, I can refresh the webpage and make changes to input values without overwriting or recreating the localStorage array.

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

Invoking a function within the directive's controller

How can I access and call the method defined within the directive controller externally? <div ng-controller="MyCtrl"> <map></map> <button ng-click="updateMap()">call updateMap()</button> </div> app.directive(&a ...

The issue with the left border color not functioning in JavaScript

Attempting to alter the border-left-color property using this script is resulting in a Uncaught SyntaxError: Unexpected token -. Is border-left-color actually supported? Javascript function logoChange() { var description = new Array (); description[0] ...

Halt the adhesion of the Bootstrap column when it hits the div section

I have a simple bootstrap row containing two columns: <div class="row"> <div class="col-xs-7"> <p>Walking together</p> </div> <div class="col-xs-5" id="stay"> <p>Joyful journey</p> </div ...

Tips for transferring express route handling to the subsequent middleware and bypassing the current block of code

Here's the current setup of my route handler in my express app: app.use('/', function(res, req, next) => { if (!authorised) next(); f1(); f2(); }); Is there a way to prevent f1() and f2() from running without adding conditional st ...

The Google timezone API is displaying an inaccurate daylight saving offset

London now has an additional +1 hour of daylight saving time. I made a request to the Google timezone API for the London timezone, but unfortunately, it is not displaying the correct time. https://maps.googleapis.com/maps/api/timezone/json?location=51.507 ...

"Enhance your website with the dynamic duo of Dropzone

Currently, I am utilizing dropzone.js and loading it through ajax. I have assigned my menu ID as "#menu". The uploaded file should display in "#div1". Unfortunately, the callback function is not functioning properly. In an attempt to troubleshoot, I repl ...

Ways to retrieve JSON data in a flutter app

I have received JSON data from a server that I need to fetch and configure in both a Pageview Builder (horizontal scroll) and a Listview Builder (vertical scroll) for a Flutter application. The Listview Builder is nested within the Pageview Builder, which ...

What is the process for moving information between files?

I have two files which are named as, employee-rates-controller.ts: private load() { return this.entityService .load(this.$scope.projectRevisionUid) .then(resp => { localStorage.removeItem('employeerates'); this.$ ...

Ways to switch out event listener when button is deactivated

I find myself in a situation where I need to switch all unauthorized controls on my UI from a hidden state to a disabled state. Additionally, I want to add a tooltip with unauthorized text and have the control display this text when clicked. While I am ab ...

What is the correct way to access an element with spaces in handlebars while working with node.js?

I have an object containing values with spaces in strings. For example: object = { "group of people": [ { (...) } ], "another group of people": [ { (...) } ] } Now, I want to use this object with the handlebars helper block in my view ( ...

angular data binding returning the identifier instead of the content

I have been dealing with managed fields retrieved from a web server in the following format: { "fields":{ "relationshipStatus":[ { "fieldId":4, "name":"Committed" }, { "fieldId":2, ...

How can one efficiently process a JSON array in Swift?

I am new to coding with Swift and I am attempting to send an HTTP request in Swift. Although I have managed to send the request, I am encountering difficulties parsing the response. Despite extensive research, I have not been successful in finding a solut ...

Adding a new element with Jquery when a dropdown option is selected

What is causing this issue to not function properly? <script> $(document).ready(function(){ $('#custom_field option').click(function(){ $('#custom_field_input').append('<tr><td></td> ...

What are some ways to design scrollbars with a Google Wave-like style?

Is there a way to design scrollbars similar to the ones found in Google Wave? They seem to save space and have an appealing look. I am interested in implementing these customized scrollbars on a div element, just like how Google Wave utilizes them. https: ...

Updating the button text in Angular 7

Here's a question: <button (click)="activateMotion(1)"> <img class="emotion-icon" id="positive-icon" src="" /> </button> <button (click)="activateMotion(-1)"> <img class="emotion-icon" id="negative-icon" src="" /&g ...

Collaborating on user authorization within a MEAN.JS framework

Recently, I decided to dive into the world of web application development by using MEAN.js full stack solution. Using the generators within MEAN.js, I was able to effortlessly create multiple CRUD models along with all the necessary express routes. In ad ...

Show pagination control only when there are multiple pages in AngularJS using ui-bootstrap

Currently, I am working with ui-bootstrap pagination and facing an issue where the pagination controls are still visible even when all the results are displayed on a single page. A quick glance at the image below confirms this problem. It seems like a basi ...

Determining array size with the help of a jsonpath expression - The expert in JsonPath, Stefan

Currently, I'm facing an issue while attempting to determine the size of an array or list using Stefan Goessner's JsonPath. The version I am utilizing is json-path-2.0.0. My JsonPath expression is $.orders.length and the JSON data resembles the ...

Display or conceal section based on selected checkboxes

I'm currently working on a JavaScript script that involves showing/hiding elements based on radio button and checkbox selections. The goal is to reveal a hidden section when certain checkboxes are checked, as illustrated in the screenshot below: http ...

Decoding JSON data in Objective-C

When processing the contents of a .json file, why is it that a string like "jamie's" appears as "jamie &#039;s"? Can anyone explain this phenomenon? ...