Skip to content

Latest commit

 

History

History
63 lines (49 loc) · 1.46 KB

WRAPPER_JOTAI.md

File metadata and controls

63 lines (49 loc) · 1.46 KB

jotai wrapper

If you want to use MMKV with Jotai, create the following atomWithMMKV function:

import { atomWithStorage, createJSONStorage } from 'jotai/utils';
import { MMKV } from 'react-native-mmkv';

const storage = new MMKV();

function getItem(key: string): string | null {
  const value = storage.getString(key)
  return value ? value : null
}

function setItem(key: string, value: string): void {
  storage.set(key, value)
}

function removeItem(key: string): void {
  storage.delete(key);
}

function subscribe(
  key: string,
  callback: (value: string | null) => void
): () => void {
  const listener = (changedKey: string) => {
    if (changedKey === key) {
      callback(getItem(key))
    }
  }

  const { remove } = storage.addOnValueChangedListener(listener)

  return () => {
    remove()
  }
}

export const atomWithMMKV = <T>(key: string, initialValue: T) =>
  atomWithStorage<T>(
    key,
    initialValue,
    createJSONStorage<T>(() => ({
      getItem,
      setItem,
      removeItem,
      subscribe,
    })),
    { getOnInit: true }
  );

Then simply use atomWithMMKV(..) instead of atom(..) when creating an atom you'd like to persist accross app starts.

const myAtom = atomWithMMKV('my-atom-key', 'value');

Note: createJSONStorage handles JSON.stringify()/JSON.parse() when setting and returning the stored value.

See the official Jotai doc here: https://jotai.org/docs/utils/atom-with-storage