astoilkov / use-local-storage-state

React hook that persists data in localStorage
MIT License
1.1k stars 41 forks source link

Add `enable` option #68

Closed zdila closed 3 months ago

zdila commented 4 months ago

Please add enable option. In our app we may not use localStorage unless user allows it. If enable is false then use memory only.

astoilkov commented 4 months ago

I'm currently considering adding an option like storage that will allow the support for localStorage, sessionStorage, and custom scenarios like yours — localStorage + memoryStorage. However, I'm not yet ready with the details.

For now, you can just throw an error inside the serializer.stringify method and this will enable memoryStorage.

(pseudo code, haven't tested it)

const serializer = createMemo(() => {
  return enabled ? undefined : { stringify() { throw new Error() }, parse() { throw new Error() }
}, [enabled])
useLocalStorageState(key, {
  serializer
})
astoilkov commented 3 months ago

I've created a new package that supports a storage option and can support this scenario — https://github.com/astoilkov/use-storage-state. I hope this helps.

I'm closing this as I won't be implementing an enable option (at least for now).