beekai-oss / little-state-machine

📠 React custom hook for persist state management

Home Page:https://lrz5wloklm.csb.app/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Method to work around disabled cookies in browser

MattL75 opened this issue · comments

Hi! We are trying to make LSM work with disabled cookies in the browser. This disables localStorage and sessionStorage in most browsers. This makes even trying to access window.sessionStorage return an access denied exception.

Our solution is to call setStorageType and save to app memory if sessionStorage is disabled.

// Run this only if sessionStorage is disabled or does not exist
const state = {}  
setStorageType({
  setItem: (key, value) => {
    state[key] = value
  },
  getItem: item => state[item],
})

Now normally this should work, but there appears to be a line in the LSM source that depends on sessionStorage being enabled, making our app crash.

let storageType: Storage = isClient
  ? window.sessionStorage
  : {
      getItem: payload => payload,
      setItem: (payload: string) => payload,
      clear: () => {},
      length: 0,
      key: (payload: number) => payload.toString(),
      removeItem: () => {},
    };

In the code above, window.sessionStorage is called, but this crashes our app if it is not available. Of course, we could (try to) use require with a try-catch instead of imports, but we'd rather avoid that.

Would you guys be open to returning null/undefined/otherwise ignore the error if window.sessionStorage is not allowed?

Thanks!

Added a PR with the implementation that I think works best. @bluebill1049 let me know if this works for you or if you want changes :)