javascriptcookiesjs-cookie

Set and Get array from cookies with js-cookie and JSON.parse


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.


Solution

  • 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