Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Appending localStorage with dynamic content

I am generating image coordinates at various locations within a image which I am saving to a localStorage item. For example:

var coords = [];
coords.push(Math.round(dragStopLocation.x),Math.round(dragStopLocation.y));

The above stores the values in coords variable. I am setting this to localStorage using:

localStorage.setItem('coords', JSON.stringify(coords));

This as a standalone code works well.

Since, the item coords is dynamic and many arrays of coords is possible, I want to append the item coords with new arrays. I am using the following code:

//Save the original coords items in a variable

var old_coords = localStorage.getItem('coords');

//append

if (old_coords === null) {
        localStorage.setItem('coords', JSON.stringify(coords));
      } else {
        localStorage.setItem('coords', old_coords + JSON.stringify(coords));  
      }

I tried one more variation of this by including a comma between old_coords and coords

localStorage.setItem('coords', old_coords + ',' + JSON.stringify(coords)); 

The problem I am facing is when I am trying to get the items of the coords from a different function.

function getArray() {

  items = JSON.parse(localStorage.getItem('coords'));  

  var size = 9;
  var newarr = [];
  for (var i = 0; i < items.length; i+=size) {
      newarr.push(items.slice(i, i+size));  
  }
  return newarr;
}

This is were I am facing the following error:

Uncaught SyntaxError: Unexpected token [ in JSON at position 4

When I use a comma, I get the same error but instead of '[ I get ,.

I tried replicating this with a simple example:

localStorage.removeItem('items');

function appendToStorage(name, data){
  var old = localStorage.getItem(name);
  if(old === null || old === undefined) {
      localStorage.setItem(name,data);
    } else {
      localStorage.setItem(name, old +"," + data);
    }
  }

items1 = ['image1','place','name',10,20,30,40,50,60];
appendToStorage('items', items1);
localStorage.getItem('items');

items2 = ['image2','place','name',11,21,31,41,51,61]
appendToStorage('items', items2);
localStorage.getItem('items');

This works perfectly...however the original code gives errors.

like image 579
Apricot Avatar asked Nov 22 '25 21:11

Apricot


1 Answers

Try this

var old_coords = localStorage.getItem('coords');
var coords = [{x: 32, y: 24}, {x: 21, y: 43}];
if (old_coords === null) {
    localStorage.setItem('coords', JSON.stringify(coords));
} else {
    old_coords = JSON.parse(old_coords);
    var new_coords = old_coords;
    coords.forEach(function(item){
        new_coords.push(item);             
    }) 

    localStorage.setItem('coords', new_coords);  
}

Note

Suppose If your coords is like var coords = [{x: 10, y: 12}, {x: 12, y: 13}] then JSON.stringify(coords) will return "[{"x":10,"y":12},{"x":12,"y":13}]"

Problem with your Approach

var coords = [{x: 10, y: 12}, {x: 12, y: 13}]
localStorage.setItem('coords', JSON.stringify(coords));

var old_coords = JSON.stringify(coords); // "[{"x":10,"y":12},{"x":12,"y":13}]"
coords = [{x: 32, y: 43}, {x: 44, y: 21}];
var new_coords = old_coords + JSON.stringify(coords); // "[{"x":10,"y":12},{"x":12,"y":13}][{"x":32,"y":43},{"x":44,"y":21}]"

localStorage.setItem('coords', new_coords); 

Now When you will do localStorage.getItem('coords'); you will get "[{"x":10,"y":12},{"x":12,"y":13}][{"x":32,"y":43},{"x":44,"y":21}]", which clearly is not a valid JSON, and hence when you try to do JSON.parse() (which you are doing in your getArray method) it will throw an error

Uncaught SyntaxError: Unexpected token [ in JSON at .....

In your second Example it works because

localStorage.removeItem('items');

function appendToStorage(name, data){
   var old = localStorage.getItem(name);
   if(old === null || old === undefined) {
       localStorage.setItem(name,data);
   } else {
       localStorage.setItem(name, old +"," + data);
   }
}

items1 = ['image1','place','name',10,20,30,40,50,60];
appendToStorage('items', items1);
localStorage.getItem('items'); 

// "image1,place,name,10,20,30,40,50,60", as you can see the difference its not stored as previous as - ["image1,place,name,10,20,30,40,50,60"], it stored without `[` and `]` brackets. 

items2 = ['image2','place','name',11,21,31,41,51,61]
appendToStorage('items', items2);
localStorage.getItem('items');
//"image1,place,name,10,20,30,40,50,60,image2,place,name,11,21,31,41,51,61", which is a **valid JSON**, 

Difference

var items2 = ['image2','place','name',11,21,31,41,51,61]
localStorage.setItem('items', items2);
localStorage.getItem('items'); // "image2,place,name,11,21,31,41,51,61"


var items2 = ['image2','place','name',11,21,31,41,51,61]
localStorage.setItem('items', JSON.stringify(items2));
localStorage.getItem('items'); // "["image2","place","name",11,21,31,41,51,61]"

As you can see if you stringify and store it will get stored as ---- "["image2","place","name",11,21,31,41,51,61]" and if you store it directly it will be stored as --- "image2,place,name,11,21,31,41,51,61"

like image 193
Pawan Singh Avatar answered Nov 25 '25 11:11

Pawan Singh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!