bendotcodes/cookies

Inconsistent change listener for cookie removal

niksauer opened this issue · 2 comments

Before upgrading to v7.0.2 (from v6.1.1), I observed the following events when removing a cookie:

console.log
    {
      name: 'testCookie',
      value: undefined,
      options: { path: '/', expires: 1970-01-31T23:00:01.000Z, maxAge: 0 }
    }

      at Array.onCookieChange (src/hooks/useCookieState.ts:75:15)

  console.log
    { name: 'testCookie', value: undefined }

      at Array.onCookieChange (src/hooks/useCookieState.ts:75:15)
          at Set.forEach (<anonymous>)

  console.log
    { name: 'Max-Age', value: undefined }

      at Array.onCookieChange (src/hooks/useCookieState.ts:75:15)
          at Set.forEach (<anonymous>)

  console.log
    { name: 'Path', value: undefined }

      at Array.onCookieChange (src/hooks/useCookieState.ts:75:15)
          at Set.forEach (<anonymous>)

  console.log
    { name: 'Expires', value: undefined }

      at Array.onCookieChange (src/hooks/useCookieState.ts:75:15)
          at Set.forEach (<anonymous>)

which has now changed to:

console.log
      {
        name: 'testCookie',
        value: undefined,
        options: { path: '/', expires: 1970-01-31T23:00:01.000Z, maxAge: 0 }
      }

      at Array.onCookieChange (src/hooks/useCookieState.ts:75:15)

    console.log
      { name: 'testCookie', value: '' }

      at Array.onCookieChange (src/hooks/useCookieState.ts:75:15)
          at Set.forEach (<anonymous>)

    console.log
      { name: 'Max-Age', value: 0 }

      at Array.onCookieChange (src/hooks/useCookieState.ts:75:15)
          at Set.forEach (<anonymous>)

    console.log
      { name: 'Path', value: '/' }

      at Array.onCookieChange (src/hooks/useCookieState.ts:75:15)
          at Set.forEach (<anonymous>)

    console.log
      { name: 'Expires', value: 'Sat, 31 Jan 1970 23:00:01 GMT' }

      at Array.onCookieChange (src/hooks/useCookieState.ts:75:15)
          at Set.forEach (<anonymous>)

The problem being that the new value can be both undefined and "" when a cookie is removed, thus making my React hook think that the value is the empty string instead of undefined. Is this expected? If so, I can always treat the empty string as undefined, although I would prefer the previous consistent bevahior.

Looking at the changes between versions, I believe this commit had an effect on this 99ba53f.

eXon commented

Hi,

The previous code was unfortunately broken for many other use-cases. The way this library remove cookies is by setting them empty with a past expiration date. However, the browser might still have the cookie until you refresh the page making an empty and deleted cookie impossible to differeciate. I will need to dig more into this on how we can fix it.