Skip to content
Closed
Show file tree
Hide file tree
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
19 changes: 13 additions & 6 deletions src/useLocalStorageState.ts
Original file line number Diff line number Diff line change
Expand Up @@ -63,8 +63,8 @@ function useLocalStorage<T>(
stringify: (value: unknown) => string = JSON.stringify,
): LocalStorageState<T | undefined> {
// we keep the `parsed` value in a ref because `useSyncExternalStore` requires a cached version
const storageItem = useRef<{ string: string | null; parsed: T | undefined }>({
string: null,
const storageItem = useRef<{ string: string | null | undefined; parsed: T | undefined }>({
string: undefined,
parsed: undefined,
})

Expand Down Expand Up @@ -110,19 +110,21 @@ function useLocalStorage<T>(
// issues that were caused by incorrect initial and secondary implementations:
// - https://github.com/astoilkov/use-local-storage-state/issues/30
// - https://github.com/astoilkov/use-local-storage-state/issues/33
if (defaultValue !== undefined && string === null) {
if (defaultValue !== undefined && string === null && !inMemoryData.has(key)) {
// reasons for `localStorage` to throw an error:
// - maximum quota is exceeded
// - under Mobile Safari (since iOS 5) when the user enters private mode
// `localStorage.setItem()` will throw
// - trying to access localStorage object when cookies are disabled in Safari throws
// "SecurityError: The operation is insecure."
// eslint-disable-next-line no-console
goodTry(() => {
// - localStorage is `null` in Firefox when `dom.storage.enabled` is `false`
try {
const string = stringify(defaultValue)
localStorage.setItem(key, string)
storageItem.current = { string, parsed: defaultValue }
})
} catch {
inMemoryData.set(key, defaultValue)
}
}

return storageItem.current.parsed
Expand Down Expand Up @@ -159,6 +161,11 @@ function useLocalStorage<T>(

inMemoryData.delete(key)

// reset the sentinel so getSnapshot re-parses the value (important when localStorage
// is unavailable and the string stays `null` — without this, `null !== null` would be
// false and the parsing branch would be skipped)
storageItem.current.string = undefined

triggerCallbacks(key)
}, [key])

Expand Down
105 changes: 105 additions & 0 deletions test/browser.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -705,6 +705,111 @@ describe('useLocalStorageState()', () => {
})
})

describe('localStorage is null (Firefox with dom.storage.enabled: false)', () => {
test('returns defaultValue when localStorage is null', () => {
vi.spyOn(window, 'localStorage', 'get').mockReturnValue(null as any)

const { result } = renderHook(() =>
useLocalStorageState('todos', { defaultValue: ['first', 'second'] }),
)

const [todos] = result.current
expect(todos).toStrictEqual(['first', 'second'])
})

test('isPersistent is true when value equals defaultValue and localStorage is null', () => {
vi.spyOn(window, 'localStorage', 'get').mockReturnValue(null as any)

const { result } = renderHook(() =>
useLocalStorageState('todos', { defaultValue: ['first', 'second'] }),
)

const [, , { isPersistent }] = result.current
expect(isPersistent).toBe(true)
})

test('isPersistent is false when value is changed and localStorage is null', () => {
vi.spyOn(window, 'localStorage', 'get').mockReturnValue(null as any)

const { result } = renderHook(() =>
useLocalStorageState('todos', { defaultValue: ['first', 'second'] }),
)

act(() => {
const setTodos = result.current[1]
setTodos(['third', 'forth'])
})

const [todos, , { isPersistent }] = result.current
expect(todos).toStrictEqual(['third', 'forth'])
expect(isPersistent).toBe(false)
})

test('setValue works when localStorage is null', () => {
vi.spyOn(window, 'localStorage', 'get').mockReturnValue(null as any)

const { result } = renderHook(() =>
useLocalStorageState('todos', { defaultValue: ['first', 'second'] }),
)

act(() => {
const setTodos = result.current[1]
setTodos(['third', 'forth'])
})

const [todos] = result.current
expect(todos).toStrictEqual(['third', 'forth'])
})

test('setValue with callback works when localStorage is null', () => {
vi.spyOn(window, 'localStorage', 'get').mockReturnValue(null as any)

const { result } = renderHook(() =>
useLocalStorageState('todos', { defaultValue: ['first', 'second'] }),
)

act(() => {
const setTodos = result.current[1]
setTodos((value) => [...value, 'third'])
})

const [todos] = result.current
expect(todos).toStrictEqual(['first', 'second', 'third'])
})

test('removeItem works when localStorage is null', () => {
vi.spyOn(window, 'localStorage', 'get').mockReturnValue(null as any)

const { result } = renderHook(() =>
useLocalStorageState('todos', { defaultValue: ['first', 'second'] }),
)

act(() => {
const setTodos = result.current[1]
setTodos(['third', 'forth'])
})

act(() => {
const removeItem = result.current[2].removeItem
removeItem()
})

const [todos] = result.current
expect(todos).toStrictEqual(['first', 'second'])
})

test('returns undefined when no defaultValue and localStorage is null', () => {
vi.spyOn(window, 'localStorage', 'get').mockReturnValue(null as any)

const { result } = renderHook(() =>
useLocalStorageState('todos'),
)

const [todos] = result.current
expect(todos).toBe(undefined)
})
})

describe('"serializer" option', () => {
test('can serialize Date from initial value', () => {
const date = new Date()
Expand Down