@statesync/persistence / loadPersistedSnapshot
Function: loadPersistedSnapshot()
ts
function loadPersistedSnapshot<T>(
storage,
applier,
onErrorOrOptions?,
loadOptions?): Promise<SnapshotEnvelope<T> | null>;Defined in: persistence/src/persistence-applier.ts:477
Loads a persisted snapshot from storage, validates it, optionally migrates it, and applies it to the given applier.
Use this function to hydrate application state from cache before starting a live sync connection. The function performs several checks in order:
- Load -- reads the snapshot (with metadata if the backend supports it)
- TTL check -- discards expired snapshots unless
ignoreTTLis set - Integrity check -- verifies hash if
verifyHashis set and a hash exists - Revision validation -- ensures the revision string is canonical
- Migration -- upgrades the data if the stored schema version is outdated
- Custom validation -- runs the user-supplied validator (if any)
- Apply -- delegates to the applier
Returns the loaded snapshot on success, or null if nothing was stored, validation failed, the cache expired, or any other error occurred.
This function supports two call signatures for backward compatibility:
loadPersistedSnapshot(storage, applier, options)-- preferredloadPersistedSnapshot(storage, applier, onError, options)-- legacy
Type Parameters
| Type Parameter | Description |
|---|---|
T | The shape of the application state. |
Parameters
| Parameter | Type | Description |
|---|---|---|
storage | StorageBackend<T> | The storage backend to load from. |
applier | { apply: void | Promise<void>; } | An object with an apply method to receive the loaded snapshot. |
applier.apply | - | |
onErrorOrOptions? | | LoadOptions<T> | (context) => void | Either a LoadOptions object (preferred) or an error callback function (legacy signature). |
loadOptions? | LoadOptions<T> | Load options when the third argument is an error callback (legacy signature only). |
Returns
Promise<SnapshotEnvelope<T> | null>
The loaded and applied snapshot, or null if loading/validation failed.
Example
typescript
const cached = await loadPersistedSnapshot(storage, applier, {
migration: {
currentVersion: 3,
migrations: {
1: (v1) => ({ ...v1, newField: 'default' }),
2: (v2) => ({ ...v2, renamedField: v2.oldField }),
},
},
});
if (cached) {
console.log('Restored from cache, revision:', cached.revision);
}