To set a cookie using the js-cookie library in JavaScript, you can use the set
method:
Cookies.set('name', 'value', { expires: 7 });
This will set a cookie with the name “name” and value “value”, which will expire in 7 days.
You can also pass an array as the value of the cookie:
Cookies.set('name', ['value1', 'value2', 'value3'], { expires: 7 });
This will set a cookie with the name “name” and an array of values as the value. The array will be stored as a string in the cookie, with the values separated by commas.
You can retrieve the array from the cookie using the get
method:
const cookieValues = Cookies.get('name');
This will return a string representation of the array, which you can then split into an actual array using the split
method:
const cookieArray = cookieValues.split(',');
You can then access the individual values of the array using array notation:
console.log(cookieArray[0]); // Outputs "value1" console.log(cookieArray[1]); // Outputs "value2" console.log(cookieArray[2]); // Outputs "value3"
Last modified: January 13, 2023