4

I'm using js-cookie to store data and get them back, I'm trying to sore an array variable but I have trouble mantaining its format. This is the process that create, retrive, change and save data of the cookie, it works but just the first time, as I'm not able to

// store array in cookie  
Cookies.set('points', '0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0', { expires: 30 });

// get data from cookie into a variable (becomes a string)  
points = Cookies.get('points');

// convert to object with (length 12)
points = JSON.parse("[" + points + "]");

// change value of the array in the varable position
points[playerId]++;

// save data in cookie
Cookies.set('points', points, {expires: 30});

This works only the first time, any subsequent time I get error and the array become length 1. I'm sure it's because I'm missing squarebrackets but if I try:

Cookies.set('points', '[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]', { expires: 30 });

the variable becomes an object with lenght 1 and it does not work.

Artemis
  • 589
  • 1
  • 6
  • 19

1 Answers1

4

The reason it fails the second time is that you pass to Cookies.set an array as second argument, making assumptions that this will end up as a comma separated string in the cookie. But js-cookie will in that case do the conversion to string by adding the square brackets.

So the very quick solution is to change this:

Cookies.set('points', points, {expires: 30});

to:

Cookies.set('points', points.toString(), {expires: 30});

However, it is better to encode and decode with JSON.stringify and JSON.parse without doing any string manipulation "yourself", like this:

var points = Array(12).fill(0);
Cookies.set('points', JSON.stringify(points), { expires: 30 });
var points = JSON.parse(Cookies.get('points'));
points[0]++;
Cookies.set('points', JSON.stringify(points), {expires: 30});
// ...etc
trincot
  • 317,000
  • 35
  • 244
  • 286
  • If I try `var points = JSON.parse(Cookies.get('points'));` I get `SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data` in the console, I think it's because of the square brackets, the rest works. – Artemis Dec 20 '19 at 15:48
  • If you start from scratch, with the final code block I provided, making sure the `Cookes.set` is executed before any `Cookies.get`, it will work without error. The square brackets are part of JSON notation, so that is not the problem. You can always inspect what the value of `Cookies.get('points')` is without doing the `JSON.parse`, so you can see what the problematic value is. – trincot Dec 20 '19 at 15:54