useCookie icon indicating copy to clipboard operation
useCookie copied to clipboard

Set/Get object transparently

Open kedoska opened this issue 3 years ago • 1 comments

Set an object

const [user, setUser] = useCookie('user', {username: 'test', id: 1000})

Get an object

const {username, id} = getCookie('user')

kedoska avatar Aug 27 '20 16:08 kedoska

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 
  }

tylerwolff avatar Aug 28 '20 01:08 tylerwolff