Andres
Andres

Reputation: 123

Duplicate key is getting set in Javascript Cookie

My issue is that the JS cookie gets set with two "viewmore" keys. Here "viewmore" is set to true and false. Can anyone help diagnose please!?

 > document.cookie
    "viewmore=true; SESSID=fjs0fmojglrih7; viewmore=false; user=1"

Shouldn't the "viewmore" key be getting overwritten and not duplicated with a different value?

Code that didn't work:

document.cookie = "viewmore=false";
document.cookie = "viewmore=true";

Code that worked: needed an expiry set

var now = new Date();
now.setTime(now.getTime() + 1 * 3600 * 1000);

document.cookie = "viewmore=false; expires=" + now.toUTCString() + "; path=/";
document.cookie = "viewmore=true; expires=" + now.toUTCString() + "; path=/";

Upvotes: 8

Views: 2445

Answers (1)

Andres
Andres

Reputation: 123

See above post for working code that fixed my problem.

Seems like it should be considered a good habit to set an expiry with cookies.

Upvotes: 1

Related Questions