docs/recipes/atom-with-toggle-and-storage.mdx
atomWithToggleAndStorageis likeatomWithTogglebut also persist the state anytime it changes in given storage usingatomWithStorage.
Here is the source:
import { WritableAtom, atom } from 'jotai'
import { atomWithStorage } from 'jotai/utils'
export function atomWithToggleAndStorage(
key: string,
initialValue?: boolean,
storage?: any,
): WritableAtom<boolean, [boolean?], void> {
const anAtom = atomWithStorage(key, initialValue, storage)
const derivedAtom = atom(
(get) => get(anAtom),
(get, set, nextValue?: boolean) => {
const update = nextValue ?? !get(anAtom)
void set(anAtom, update)
},
)
return derivedAtom as WritableAtom<boolean, [boolean?], void>
}
And how it's used:
import { atomWithToggleAndStorage } from 'XXX'
// will have an initial value set to false & get stored in localStorage under the key "isActive"
const isActiveAtom = atomWithToggleAndStorage('isActive')
The usage in a component is also the same as atomWithToggle.