0

My localStorage is only saving a few variables (3) of similar names, and then proceeding to override the last variable with the new value.

What I am trying to do is add variables into localStorage that have a name and a number attached to them such as Test1, Test2, Test3, etc.

The only issue is that after the third element, in this case Test3, the key gets overridden to Test4 and the value changes to the new value. This happens forever as long as the word Test is the same.

I can add other values just fine, but only up to 3 of the same root word.

This is the code I am using to add the elements:

const AddToLocalStorage = (type, contents) => {
    let ind = 0;
    Object.keys(localStorage).forEach(function (key) {
        if (key == (type + ind)) {
            ind++;
        } else {
            return;
        }
    });
    localStorage.setItem((type + ind), JSON.stringify(contents));
}

type is a string such as Test
contents is the value stored

Thanks in advance :)

Edit - Can you clarify how to call the AddToLocalStorage function

AddToLocalStorage("Test", "value");

In localStorage this would set like { "Test0", "value" }

Gunnarhawk
  • 437
  • 3
  • 12
  • The `setItem` is outside the `forEach` so it makes sense only the last value is written. – 0stone0 May 24 '21 at 16:51
  • @0stone0 Can you elaborate? Why would the `setItem` need to be inside the `forEach` loop? – Gunnarhawk May 24 '21 at 16:53
  • Could you please clarify how you call the `AddToLocalStorage` function? – 0stone0 May 24 '21 at 16:54
  • Why not use an array? – adiga May 24 '21 at 16:59
  • @adiga I am using `localStorage` because I am using the values set on multiple pages. If you mean using an array in `localStorage`, how would I do this? I thought you could only set strings – Gunnarhawk May 24 '21 at 17:02
  • `JSON.stringify()` always returns an string. Something like this: `const AddToLocalStorage = (type, contents) => { const arr = JSON.parse( localStorage.getItem(type) || "[]" ); arr.push(contents); localStorage.setItem(type, JSON.stringify(arr) ); }` – adiga May 24 '21 at 17:12

1 Answers1

2

First of all, JavaScript Object Property order isn't guaranteed, therefore you're probably not receiving the keys in the same order as your browser shows them


That said, lets add some console.log's to debug the code:

const AddToLocalStorage = (type, contents) => {
    let ind = 0;
    console.log('Existing keys', Object.keys(localStorage));
    Object.keys(localStorage).forEach(function (key) {
        if (key == (type + ind)) {
            ind++;
        } else {
            return;
        }
    });
    console.log('Set', (type + ind))
    localStorage.setItem((type + ind), JSON.stringify(contents));
}
AddToLocalStorage("Test", "value1");

On the second run, this logs:

Existing keys (3) ["Test2", "Test0", "Test1"]
Set Test2

Here we can see that (type + ind) will be Test2, because (key == (type + ind)) will be true for Test1 and Test2.

Since Test2 already exists, you'll override the existing value.

0stone0
  • 34,288
  • 4
  • 39
  • 64
  • That was it, thank you. Such a stupid mistake – Gunnarhawk May 24 '21 at 17:11
  • 1
    Basically the "error" here is assuming that `localStorage` will give keys back in the same order that you set them. That is an incorrect assumption. The correct way to do this would be to either save one big array in storage, or have a separate item in storage called `nextIndex` or whatever. – Niet the Dark Absol May 24 '21 at 17:12
  • Yea @Nietthedarkabsol, trying to find a SO post to link to to let OP know more about this. So far not found – 0stone0 May 24 '21 at 17:13
  • 1
    @0stone0 Try https://stackoverflow.com/questions/5525795/does-javascript-guarantee-object-property-order – Niet the Dark Absol May 24 '21 at 17:15