Synchronizer
Synchronizer is a utility that allows you to synchronize store with something external like localStorage, database, device storage (MMKV, AsyncStorage) etc.
type Synchronizer<T> = { value: T, subscribe?: (update: (value: T) => void, key: string) => void, // If synchronizer doesn't have data that matches passed key, it should throw getSnapshot: (key: string) => T | Promise<T>, update: (value: T, key: string) => void}
There is already implementation for persisting data on both platforms (react and react-native).
import { storage } from 'stan-js/storage'
It takes two parameters - first is initial value, and the second one (which is optional) is options object with key (if the key isn’t passed stan-js will pass key from the store), serialize and deserialize functions.
Syncing values using synchronizer
Section titled “Syncing values using synchronizer”import { createStore } from 'stan-js'import { storage } from 'stan-js/storage'
const { useStore } = createStore({ counter: storage(0, { storageKey: 'counter-key' }), // number user: storage<string>(), // string | undefined cart: [] as Array<CartItem>})
Custom storage
Section titled “Custom storage”If you want to customize storage, for example to use your own mmkv instance - you can use createStorage
factory function. It creates a new storage function that you can use across your app.
import { createStorage } from 'stan-js/storage'import { MMKV } from 'react-native-mmkv'
const encryptedMMKV = new MMKV({ encryptionKey: 'my-encryption-key'})
const myStorage = createStorage({ mmkvInstance: encryptedMMKV,})
Or if you want to store more complex objects that aren’t supported by JSON you can pass custom serialize
and deserialize
functions. For example, you can use superjson package:
import { createStore } from 'stan-js'import { createStorage } from 'stan-js/storage'import superjson from 'superjson'
const superJsonStorage = createStorage({ serialize: superjson.stringify, deserialize: superjson.deserialize})
const { useStore } = createStore({ user: superJsonStorage(new Set())})