Skip to content
New issue

Have a question about this project? # for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “#”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? # to your account

feat(util): atomWithStorage #394

Merged
merged 7 commits into from
May 9, 2021
Merged
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
1 change: 1 addition & 0 deletions src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,3 +11,4 @@ export { freezeAtom, atomFrozenInDev } from './utils/freezeAtom'
export { splitAtom } from './utils/splitAtom'
export { atomWithDefault } from './utils/atomWithDefault'
export { waitForAll } from './utils/waitForAll'
export { atomWithStorage } from './utils/atomWithStorage'
54 changes: 54 additions & 0 deletions src/utils/atomWithStorage.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
import { atom, PrimitiveAtom } from 'jotai'
import type { SetStateAction } from '../core/types'

type Storage<Value> = {
getItem: (key: string) => Value | Promise<Value>
setItem: (key: string, newValue: Value) => void | Promise<void>
}

const defaultStorage: Storage<unknown> = {
getItem: (key) => {
const storedValue = localStorage.getItem(key)
if (storedValue === null) {
throw new Error('no value stored')
}
return JSON.parse(storedValue)
},
setItem: (key, newValue) => {
localStorage.setItem(key, JSON.stringify(newValue))
},
}

export function atomWithStorage<Value>(
key: string,
initialValue: Value,
storage: Storage<Value> = defaultStorage as Storage<Value>
): PrimitiveAtom<Value> {
const getInitialValue = () => {
try {
return storage.getItem(key)
} catch {
return initialValue
}
}

const baseAtom = atom(initialValue)

baseAtom.onMount = (setAtom) => {
Promise.resolve(getInitialValue()).then(setAtom)
}

const anAtom = atom(
(get) => get(baseAtom),
(get, set, update: SetStateAction<Value>) => {
const newValue =
typeof update === 'function'
? (update as (prev: Value) => Value)(get(baseAtom))
: update
set(baseAtom, newValue)
storage.setItem(key, newValue)
}
)

return anAtom
}
47 changes: 47 additions & 0 deletions tests/utils/atomWithStorage.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
import React, { Fragment } from 'react'
import { fireEvent, render } from '@testing-library/react'
import { Provider as ProviderOrig, useAtom } from '../../src/index'
import { atomWithStorage } from '../../src/utils'

const Provider = process.env.PROVIDER_LESS_MODE ? Fragment : ProviderOrig

const storageData: Record<string, number> = {
count: 10,
}
const dummyStorage = {
getItem: (key: string) => {
if (!(key in storageData)) {
throw new Error('no value stored')
}
return storageData[key]
},
setItem: (key: string, newValue: number) => {
storageData[key] = newValue
},
}

it('simple count', async () => {
const countAtom = atomWithStorage('count', 1, dummyStorage)

const Counter: React.FC = () => {
const [count, setCount] = useAtom(countAtom)
return (
<>
<div>count: {count}</div>
<button onClick={() => setCount((c) => c + 1)}>button</button>
</>
)
}

const { findByText, getByText } = render(
<Provider>
<Counter />
</Provider>
)

await findByText('count: 10')

fireEvent.click(getByText('button'))
await findByText('count: 11')
expect(storageData.count).toBe(11)
})