Last active
October 1, 2024 11:34
-
-
Save MarceloPrado/ff48083f3cf21818d6dbe7fdfd969c4d to your computer and use it in GitHub Desktop.
A simple Jotai atom with storage using react-native-mmkv backend
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// `storage` is just a MMKV instance from `react-native-mmkv` | |
import { storage } from "@/app/storage"; | |
import { atomWithStorage } from "jotai/utils"; | |
const defaultOpts = { getOnInit: true }; | |
export const atomWithMmkvBooleanStorage = ( | |
key: string, | |
initialValue: boolean | |
) => | |
atomWithStorage( | |
key, | |
initialValue, | |
{ | |
getItem(key, initialValue: boolean) { | |
return storage.getBoolean(key) ?? initialValue; | |
}, | |
setItem: (key, newValue) => { | |
storage.set(key, newValue); | |
}, | |
removeItem: (key) => { | |
storage.delete(key); | |
}, | |
}, | |
defaultOpts | |
); | |
export const atomWithMmkvStringStorage = (key: string, initialValue: string) => | |
atomWithStorage( | |
key, | |
initialValue, | |
{ | |
getItem(key, initialValue: string) { | |
return storage.getString(key) ?? initialValue; | |
}, | |
setItem: (key, newValue) => { | |
storage.set(key, newValue); | |
}, | |
removeItem: (key) => { | |
storage.delete(key); | |
}, | |
}, | |
defaultOpts | |
); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { atomWithMmkvBooleanStorage } from "./atomWithMmkStorage"; | |
import { atom } from "jotai"; | |
export function atomWithToggleAndStorage(key: string, initialValue: boolean) { | |
const anAtom = atomWithMmkvBooleanStorage(key, initialValue); | |
const derivedAtom = atom( | |
(get) => get(anAtom), | |
(get, set, nextValue?: boolean) => { | |
const update = nextValue ?? !get(anAtom); | |
set(anAtom, update); | |
} | |
); | |
return derivedAtom; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment