QueryPersistence unstable
Persists persist: true query Successes to a KeyValueStore and restores
them into the next cache so reloads show the last data while refetching,
including offline.
Provide layerKvs to a mount or Query.layer() with a KeyValueStore
beneath it. Without the Layer, persist: true does nothing.
- On build,
layerKvsloads entries underprefixbefore mount (so the first frame has saved data) and prunes entries pastmaxAge, under anotherversion, or unparseable. Entries that fail to decode are dropped on first read. - Restored entries start stale with their original timestamp: a watch or
getrefetches immediately, and a failed refetch keeps the saved value aspreviousSuccess(including fetches that fail before hydration adoption). - Successes from fetches, stream emissions, Command
writes, and infinite queryloadMore/resetare saved. Optimistic patches and Failures are not. Writes batch for one second while visible. Hiding the app or saving while hidden skips that delay, including while offline. Each batch waits for the previous write to finish, and Scope close flushes any remaining writes.
Gotchas
- Server hydration (
~query) wins; omitted entries restore after adoption. - Queries whose args, success, or error Schema holds
Schema.Redactedare never saved. - Signed-out users' entries aren't cleared automatically; include the user
id in
prefix. - Saved entries remain in memory (encoded) for the session alongside decoded cache values.
Example A reload that is offline
import { Effect, Layer, Schema } from "effect"import { KeyValueStore } from "effect/persistence"import { Query, QueryPersistence } from "effect/ui"
let online = true
class GetNotes extends Query.Service<GetNotes>()("notes/GetNotes", { success: Schema.Array(Schema.String), error: Schema.String, staleTime: "30 seconds", persist: true}) { static readonly layer = this.toLayer(() => online ? Effect.succeed(["draft"]) : Effect.fail("offline") )}
const program = Effect.gen(function*() { // One store, two sessions: the second is the reload. const store = Layer.succeed(KeyValueStore.KeyValueStore, yield* KeyValueStore.KeyValueStore) const session = Layer.merge(GetNotes.layer, Query.layer()).pipe( Layer.provide(QueryPersistence.layerKvs({ prefix: "notes", maxAge: "7 days" })), Layer.provide(store) ) yield* GetNotes.get({}).pipe(Effect.provide(session)) online = false const result = yield* GetNotes.peek({}).pipe(Effect.provide(session)) return result._tag === "Success" ? result.value : []}).pipe(Effect.provide(KeyValueStore.layerMemory))
await Effect.runPromise(program) // => ["draft"]Layers
Persists persist queries to the KeyValueStore, one key per entry
under prefix.
Details
prefixnamespaces the keys. Put a user id in it to keep users apart.maxAgeis how long a saved entry is kept, from its last save. A restored Success keeps its own timestamp.versiondrops every entry saved under another one. Use a build id when a deploy changes a query's Schemas.
The Layer fails on nothing: an entry that can't be read is skipped, and a
failed save is reported through Query.Problems as a SaveFailed.
Gotchas
Throws on an invalid maxAge.
Signature
declare function layerKvs(options: { readonly maxAge: Input; readonly prefix: string; readonly version?: string;}): Layer<never, never, KeyValueStore>Problems
SaveFailed
unstable Since v4.2.0 Source
A Success of a persist query failed to encode, or the store failed to
write it. The cache is unchanged, and the store keeps what it held.
Signature
declare class SaveFailed extends Readonly<{ readonly message: string; readonly part: "encode" | "write"; readonly query: string;}> & { readonly _tag: "SaveFailed";} & Pipeable { constructor(args: { readonly message: string; readonly part: "encode" | "write"; readonly query: string; });}