ScottHamper / Cookies

JavaScript Client-Side Cookie Manipulation Library
The Unlicense
1.77k stars 170 forks source link

Type of value? #69

Open wzup opened 7 years ago

wzup commented 7 years ago

What is type of value? You pass string and don't say a word if it is possible to pass JS objects.

// Setting a cookie value 
Cookies.set('key', 'value');

Cookies.set('key', {foo: 10, bar: "BAR"}); // <== is this possible?
ScottHamper commented 7 years ago

Hey @wzup - the value must be a string, but you're right that the readme does not clearly document this! I will have to address this soon.

If you'd like to pass in an object for a value, I'd recommend first converting it to a JSON string, like so:

Cookies.set('key', JSON.stringify({foo: 10, bar: "BAR"}));

Similarly, you can use JSON.parse to deserialize the string back into an object after retrieving the cookie value with Cookies.get.

eaharonoff commented 7 years ago

@ScottHamper thank you for this library! Great work! Could we also mention that the object needs to be decoded using decodeURIComponent() prior to using JSON.parse()? Going through cookies.js I found that you do not decode the value (line 136) and defer until the value is accessed. Is there a specific reason why you choose to defer? Just curious...

ScottHamper commented 7 years ago

Hey @eaharonoff ,

Decoding is deferred to prevent an error from occurring in an edge case when there is a single cookie with an improperly encoded value. If all cookie values were decoded up-front, and a single one of the values is improperly encoded, then an error will be thrown whenever a user attempts to get any cookie value - even one that is properly encoded. To mitigate against this, the library defers decoding any specific value until it is actually asked for, so that an error will only be thrown when attempting to retrieve the value of an improperly encoded cookie.

For more detailed history on this, see #47 .

As for your other question regarding that we mention the object needs to be decoded prior to using JSON.parse - I'm not sure I understand. Cookies.js will ultimately handle the decode internally - end users of the library should not have to manually decode a cookie value. You should be able to do the following:

Cookies.set('key', JSON.stringify({ foo: 10, bar: "BAR" }));
var value = JSON.parse(Cookies.get('key'));

Let me know if I'm misunderstanding your question!

eaharonoff commented 7 years ago

Nope. You nailed it! After doing some investigation I found I needed to decode the value because I was retrieving the Cookie server side with koa context's get method. My bad!