Skip to content

Instantly share code, notes, and snippets.

@MarceloPrado
Last active April 15, 2024 13:04
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save MarceloPrado/ff48083f3cf21818d6dbe7fdfd969c4d to your computer and use it in GitHub Desktop.
Save MarceloPrado/ff48083f3cf21818d6dbe7fdfd969c4d to your computer and use it in GitHub Desktop.
A simple Jotai atom with storage using react-native-mmkv backend
// `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
);
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