Reputation: 129
I want to set cookies. I have an array and a function setCookies. In this function, I loop through myCookies array and after some manipulation I get a string. This string supposed to set cookies.
const myCookies =
[
{budgetMonth: someValue1},
{budgetDay: someValue2},
{expensesMonth: someValue3}
];
function setCookies(myCookies) {
let arr = [];
for(let i of Object.keys(myCookies)) {
let myItems = myCookies[i];
for(let y of Object.keys(myItems)) {
arr.push('document.cookie ' + '= "' + y + '=' + myItems[y] + "\"");
}
}
let stri = '';
arr.forEach(item => {
stri += item + ';'
});
return stri;
}
setCookies(myCookies);
When I log stri I see the strings listed below. Isn't it a right way to set cookie? I guess it is, but why it doesn't work? When I just type in my code document.cookie = "budgetMonth=someValue1" the cookie is set.
document.cookie = "budgetMonth=someValue1";
document.cookie = "budgetDay=someValue2";
document.cookie = "expensesMonth=someValue3";
Upvotes: 0
Views: 37
Reputation: 1131
There are several issues with your code.
the structure in which you are storing the values for the cookies is not necessarily incorrect, but writing it as myCookies = {name1: value1, name2: value2}
simplifies your code, indirectly verifies if you aren't setting the same cookie name multiple times (unless you really want to do that, setting multiple paths, for the same key, for example), and allows you to add/remove a cookie from the list later on in your code in a much more simplified way;
you are generating an array, and with that array, a string, but you aren't doing anything with any of them. To actually set up the cookie, you have to execute the code document.cookie = something.
A very simplified version of your code (untested) would be something like:
const myCookies = {
budgetMonth: someValue1,
budgetDay: someValue2,
expensesMonth: someValue3
};
function setCookies(myCookies) {
for(let k of Object.keys(myCookies)) {
document.cookie = k + "=" + myCookies[k];
}
}
setCookies(myCookies);
Upvotes: 1