useCookie
useCookie copied to clipboard
Set/Get object transparently
Set an object
const [user, setUser] = useCookie('user', {username: 'test', id: 1000})
Get an object
const {username, id} = getCookie('user')
Great idea, I like how simple this makes saving object data. However, I think this may introduce some breaking changes for people who are already manually managing what is set/get. I'm a bit hesitant to add the assumption that every non-string should be strigified. For example, undefined
may cause problems when parsing back out.
Let me look into how some other cookie libraries deal with this sort of thing. I know some popular libraries like js-cookie leave it up to the user to define how encoding/decoding works. I could also see this being set during initialization for more flexibility, maybe something along the lines of:
const [user, setUser] = useCookie('user',
{username: 'test', id: 1000},
{
encode: JSON.stringify, // or a custom function of your making
decode: JSON.parse
}