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.