Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
79 changes: 79 additions & 0 deletions src/lib/state/react/usePersistSignals.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
import { renderHook, waitFor } from "@testing-library/react"
import { describe, expect, it } from "vitest"
import type { Adapter } from "../persistence/adapters/Adapter"
import { IDENTIFIER_PERSISTENCE_KEY } from "../persistence/constants"
import type {
PersistenceEntry,
SignalPersistenceConfig,
} from "../persistence/types"
import { signal } from "../Signal"
import { usePersistSignals } from "./usePersistSignals"

const createMemoryAdapter = (
storage: Record<string, unknown> = {},
): Adapter & { storage: Record<string, unknown> } => ({
storage,
getItem: async (key: string) => storage[key],
setItem: async (key: string, value: unknown) => {
storage[key] = value
},
removeItem: async (key: string) => {
delete storage[key]
},
clear: async () => {},
})

describe("Given an entry added after the initial hydration", () => {
it("should hydrate and persist the new entry", {
timeout: 3000,
}, async () => {
const signalA = signal({ default: 0, key: "a" })
const signalB = signal({ default: 0, key: "b" })

const adapter = createMemoryAdapter({
b: {
[IDENTIFIER_PERSISTENCE_KEY]: IDENTIFIER_PERSISTENCE_KEY,
value: 7,
migrationVersion: 0,
} satisfies PersistenceEntry,
})

// biome-ignore lint/suspicious/noExplicitAny: test
const initialEntries: Array<SignalPersistenceConfig<any>> = [
{ signal: signalA, version: 0 },
]
// biome-ignore lint/suspicious/noExplicitAny: test
const updatedEntries: Array<SignalPersistenceConfig<any>> = [
{ signal: signalA, version: 0 },
{ signal: signalB, version: 0 },
]

const { result, rerender } = renderHook(
({ entries }) => usePersistSignals({ entries, adapter }),
{ initialProps: { entries: initialEntries } },
)

await waitFor(() => {
expect(result.current.isHydrated).toBe(true)
})

expect(signalB.getValue()).toBe(0)

rerender({ entries: updatedEntries })

await waitFor(() => {
expect(signalB.getValue()).toBe(7)
})

signalB.update(9)

await waitFor(
() => {
expect((adapter.storage.b as PersistenceEntry | undefined)?.value).toBe(
9,
)
},
{ timeout: 2000 },
)
})
})
15 changes: 10 additions & 5 deletions src/lib/state/react/usePersistSignals.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { concatMap, merge, of, scan, switchMap } from "rxjs"
import { merge, of, scan, switchMap } from "rxjs"
import { useLiveBehaviorSubject } from "../../binding/useLiveBehaviorSubject"
import { useObserve } from "../../binding/useObserve/useObserve"
import { useLiveRef } from "../../utils/react/useLiveRef"
Expand All @@ -20,9 +20,8 @@ export function usePersistSignals({
adapter,
}: {
/**
* Passing a new list of entries will start over the process
* once the current one is finished. Use a stable reference to avoid
* infinite loop.
* Passing a new list of entries will start over the process.
* Use a stable reference to avoid infinite loop.
*/

// biome-ignore lint/suspicious/noExplicitAny: TODO
Expand Down Expand Up @@ -51,7 +50,13 @@ export function usePersistSignals({
return merge(
of({ type: "reset" }),
entriesSubject.pipe(
concatMap((entries) =>
/**
* `persistSignals` never completes on its own (it keeps
* persisting signal updates), so a sequential operator would
* queue new entries forever. Restart the process instead
* whenever a new list is emitted.
*/
switchMap((entries) =>

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Preserve pending updates when restarting persistence

When the entries reference changes within the 500 ms throttleTime window after an existing signal update, this switchMap unsubscribes the old persistence stream and discards its pending trailing write. The replacement persistSignals then rehydrates every existing entry from the adapter, so the stale stored value overwrites the newer in-memory value and is persisted again; for example, updating a and immediately changing [a] to [a, b] loses the update to a. Restarting should flush/preserve pending values or hydrate only newly added entries rather than rehydrating unchanged signals.

Useful? React with 👍 / 👎.

persistSignals({
adapter,
entries,
Expand Down