JotaiJotai

状態
Primitive and flexible state management for React

atomWithToggleAndStorage

atomWithToggleAndStorage

atomWithToggleAndStorage is like atomWithToggle but also persist the state anytime it changes in given storage using atomWithStorage.

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 | undefined> {
const anAtom = atomWithStorage(key, initialValue, storage)
const derivedAtom = atom(
(get) => get(anAtom),
(get, set, nextValue?: boolean) => {
const update = nextValue ?? !get(anAtom)
set(anAtom, update)
}
)
return derivedAtom
}

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.