Skip to content

Commit 95932b9

Browse files
authored
fix(utils): atomWithStorage should deal with no localStorage (#951)
1 parent db3efa5 commit 95932b9

File tree

2 files changed

+44
-5
lines changed

2 files changed

+44
-5
lines changed

src/utils/atomWithStorage.ts

+8-4
Original file line numberDiff line numberDiff line change
@@ -55,10 +55,14 @@ export function createJSONStorage<Value>(
5555
export function createJSONStorage<Value>(
5656
getStringStorage: () => AsyncStringStorage | SyncStringStorage
5757
): AsyncStorage<Value> | SyncStorage<Value> {
58-
if (!getStringStorage().removeItem) {
59-
console.warn(
60-
'Missing removeItem. In the next version, it will be required.'
61-
)
58+
try {
59+
if (!getStringStorage().removeItem) {
60+
console.warn(
61+
'Missing removeItem. In the next version, it will be required.'
62+
)
63+
}
64+
} catch {
65+
// getStringStorage can throw if localStorage is not defined
6266
}
6367
return {
6468
getItem: (key) => {

tests/utils/atomWithStorage.test.tsx

+36-1
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,12 @@
11
import { Suspense } from 'react'
22
import { fireEvent, render, waitFor } from '@testing-library/react'
33
import { useAtom } from 'jotai'
4-
import { RESET, atomWithHash, atomWithStorage } from 'jotai/utils'
4+
import {
5+
RESET,
6+
atomWithHash,
7+
atomWithStorage,
8+
createJSONStorage,
9+
} from 'jotai/utils'
510
import { getTestProvider } from '../testUtils'
611

712
const Provider = getTestProvider()
@@ -180,6 +185,36 @@ describe('atomWithStorage (async)', () => {
180185
})
181186
})
182187

188+
describe('atomWithStorage (no storage) (#949)', () => {
189+
it('can throw in createJSONStorage', async () => {
190+
const countAtom = atomWithStorage(
191+
'count',
192+
1,
193+
createJSONStorage(() => {
194+
throw new Error('no storage')
195+
})
196+
)
197+
198+
const Counter = () => {
199+
const [count, setCount] = useAtom(countAtom)
200+
return (
201+
<>
202+
<div>count: {count}</div>
203+
<button onClick={() => setCount((c) => c + 1)}>button</button>
204+
</>
205+
)
206+
}
207+
208+
const { findByText } = render(
209+
<Provider>
210+
<Counter />
211+
</Provider>
212+
)
213+
214+
await findByText('count: 1')
215+
})
216+
})
217+
183218
describe('atomWithHash', () => {
184219
it('simple count', async () => {
185220
const countAtom = atomWithHash('count', 1)

0 commit comments

Comments
 (0)