Skip to content

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

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 serializer

If you want to store more complex objects that aren’t supported by JSON you can either write your own storage synchronizer or pass custom serialize and deserialize functions to the options’ parameter. For example, you can use superjson package:

import { createStore } from 'stan-js'
import { storage } from 'stan-js/storage'
import superjson from 'superjson'
const { useStore } = createStore({
user: storage(new Set(), {
serialize: superjson.stringify,
deserialize: superjson.deserialize
})
})