Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 31 additions & 1 deletion packages/use-storage/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,34 @@ const canUseDOM =
typeof window.sessionStorage !== 'undefined'
)

const createMemoryStorage = (): Storage => {
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Missing unit test on this part

const storage: { [key: string]: string | null } = {}

return {
length: Object.entries(storage).length,
clear() {
Object.keys(storage).forEach(key => {
delete storage[key]
})
},
key(index) {
return Object.values(storage)[index] ?? null
},
getItem(key) {
return storage[key] ?? null
},
setItem(key, value) {
storage[key] = value
},
removeItem(key) {
delete storage[key]
},
}
}

const getStorage = (name: 'localStorage' | 'sessionStorage') =>
canUseDOM ? window[name] : createMemoryStorage()

const subscribeStorage = (callback: () => void) => {
if (canUseDOM) {
window.addEventListener('storage', callback)
Expand All @@ -47,7 +75,9 @@ const useStorage = <T>(
): [T | null, (value: T | undefined) => void] => {
const storage = useMemo(
() =>
options?.kind === 'session' ? window.sessionStorage : window.localStorage,
options?.kind === 'session'
? getStorage('sessionStorage')
: getStorage('localStorage'),
[options?.kind],
)

Expand Down