restate / v1.0.0

API reference

Every export of @kkwaenggwari/restate 1.0 with its arguments, return values and behavior.

On this pageExportsStore methodsSaved store methodspersistedRestate optionsStatus fieldsrestateManager and scope.managerStorage adapter interface

Exports

Everything is imported from @kkwaenggwari/restate on the web and on React Native.

ExportReturnsUse it to
restate(initial, updater | options?)Store hookCreate a shared memory store.
persistedRestate(initial, options)Saved store hookCreate a store that restores and saves through storage.
useRestateScope(factory?)Factory result or scopeOwn stores in a component; destroyed after unmount.
createRestateScope()RestateScopeOwn stores outside React; call destroy() when done.
shallow(left, right)booleanCompare selections one level deep.
batch(callback)Callback resultNotify subscribers once after several changes.
restateManagerRestateManagerWait for startup data and run bulk operations on global stores.
createIndexedDBStorage(options?)RestateStorageCreate an IndexedDB adapter with a custom database or store name.
createMMKVStorage(options?)RestateStorageCreate an MMKV adapter with your own instance or configuration.

Store methods

A store is a function you call as a hook, with these methods.

MemberDescription
useStore()Returns the whole value and re-renders on each change.
useStore(selector, isEqual?)Returns the selection; re-renders when isEqual (default Object.is) reports a change.
get()Current value, without subscribing.
set(value | updater)Replace the value or compute it from the previous one. Ignored after destroy().
reset()Restore the declared initial value and return it.
subscribe(listener)Call listener(value, previous, event) after each change; returns an unsubscribe function.
subscribeSelector(selector, listener, isEqual?)Call listener only when the selection changes.
on(type, listener)Listen to events such as change, reset, save or error.
start() / stop() / isRunning()Control the updater by hand.
destroy() / isDestroyed()Release listeners and the updater. Later subscriptions throw STORE_DESTROYED.
getInitial() / getServerSnapshot() / getError()Initial value, server snapshot and the last listener error.
id / kindUnique id; memory or persistent.

Saved store methods

persistedRestate returns a store with these additional members.

MemberDescription
readyPromise that settles when the automatic load finishes, even if it failed. Check status().
save()Write the current value; resolves with the value actually written.
restore()Read the saved value into memory.
hasSaved()Whether a saved record exists.
clearStorage()Delete the saved record; memory is unchanged.
resetAndClearStorage()Reset memory to the initial value and delete the saved record.
initialize()Load again, for example after fixing a failed record.
status()Frozen status snapshot; the same object until a field changes.
useStatus(selector?, isEqual?)Hook that re-renders when the status or the selected part changes.
key / storageKey / storageLogical key, namespaced key and the adapter in use.

persistedRestate options

key is required. Every other option is optional.

OptionDefaultMeaning
keyrequiredLogical record key.
namespace"@kkwaenggwari/restate"Prefix of the stored key; an empty string disables it.
storageIndexedDB / MMKVAdapter to use instead of the platform default.
autoSavefalsetrue saves after each change; { delayMs } waits for a pause.
version / migrate1 / noneRecord version and how to upgrade older records.
validatenoneChecks values before save and after restore or migration.
serializerJSONCustom serialize and deserialize functions.
operationTimeoutMs30000Time limit for one storage operation.
maxPendingOperations256Pending operations allowed, including the active one.
maxStorageCharacters5242880Largest encoded value in UTF-16 code units.
updater / managed / serverSnapshot / onError—Same as restate options.

Status fields

status() and useStatus() return these fields.

FieldMeaning
readyThe automatic load has finished.
dirtyMemory differs from the value last loaded, saved or restored.
operationThe storage operation running now, or null.
pendingUnsettled storage operations, including the active one.
blockedAn aborted or timed-out adapter call has not settled yet.
availableWhether storage can be used.
error / observerErrorLast storage error; last status listener error.
lastSavedAt / lastRestoredAtEpoch milliseconds of the last success, or null.

restateManager and scope.manager

Each manager tracks the persistent stores registered with it.

MemberDescription
readyWaits for the stores registered at access time; rejects with BULK_OPERATION_FAILED.
saveAll(options?) / restoreAll(options?)Run save or restore for every store; { concurrency } limits parallel work.
clearStorageAll() / resetAll() / resetAllAndClearStorage()Clear records, reset memory, or both.
list() / get(idOrKey) / size()Inspect registered stores.
subscribe(listener) / status()Observe manager events and listener errors.
destroyAll()Destroy every registered store.

Storage adapter interface

Pass an object with these methods as storage. Every method may return a value or a Promise.

MethodDescription
getItem(key, context?)Return the saved string or null.
setItem(key, value, context?)Store the string.
removeItem(key, context?)Delete the record.
isAvailable?()Synchronously report whether storage can be used.
clear?() / close?()Optional clearing and cleanup.
coordinationKey?Shared object for wrappers of the same backing storage.

Search docs

Search titles, descriptions and text of every guide.