From 26362027cb782a0daf1e3dd58fb941fcc894c57f Mon Sep 17 00:00:00 2001 From: Sam Willis Date: Sun, 6 Jul 2025 13:53:13 +0100 Subject: [PATCH 1/4] ensure that all transactions are given an id --- .changeset/open-foxes-say.md | 5 +++++ packages/db/src/transactions.ts | 20 +++++--------------- 2 files changed, 10 insertions(+), 15 deletions(-) create mode 100644 .changeset/open-foxes-say.md diff --git a/.changeset/open-foxes-say.md b/.changeset/open-foxes-say.md new file mode 100644 index 0000000000..a1f248e53b --- /dev/null +++ b/.changeset/open-foxes-say.md @@ -0,0 +1,5 @@ +--- +"@tanstack/db": patch +--- + +Ensure that all transactions are given an id, fixes a potential bug with direct mutations diff --git a/packages/db/src/transactions.ts b/packages/db/src/transactions.ts index 5b5d0992a4..024c4a19bf 100644 --- a/packages/db/src/transactions.ts +++ b/packages/db/src/transactions.ts @@ -15,21 +15,8 @@ let transactionStack: Array> = [] export function createTransaction< TData extends object = Record, >(config: TransactionConfig): Transaction { - if (typeof config.mutationFn === `undefined`) { - throw `mutationFn is required when creating a transaction` - } - - let transactionId = config.id - if (!transactionId) { - transactionId = crypto.randomUUID() - } - const newTransaction = new Transaction({ - ...config, - id: transactionId, - }) - + const newTransaction = new Transaction(config) transactions.push(newTransaction) - return newTransaction } @@ -74,7 +61,10 @@ export class Transaction< } constructor(config: TransactionConfig) { - this.id = config.id! + if (typeof config.mutationFn === `undefined`) { + throw `mutationFn is required when creating a transaction` + } + this.id = config.id ?? crypto.randomUUID() this.mutationFn = config.mutationFn this.state = `pending` this.mutations = [] From d65a4c257f4bdb2efe6ba3bd63f26647fbd5255b Mon Sep 17 00:00:00 2001 From: Sam Willis Date: Sun, 6 Jul 2025 15:01:36 +0100 Subject: [PATCH 2/4] add a sequence number to transactions for sorting --- .changeset/khaki-cougars-give.md | 5 +++++ packages/db/src/collection.ts | 4 ++-- packages/db/src/transactions.ts | 19 +++++++++++++++++++ 3 files changed, 26 insertions(+), 2 deletions(-) create mode 100644 .changeset/khaki-cougars-give.md diff --git a/.changeset/khaki-cougars-give.md b/.changeset/khaki-cougars-give.md new file mode 100644 index 0000000000..5aa49b8c44 --- /dev/null +++ b/.changeset/khaki-cougars-give.md @@ -0,0 +1,5 @@ +--- +"@tanstack/db": patch +--- + +add a sequence number to transactions to when sorting we can ensure that those created in the same ms are sorted in the correct order diff --git a/packages/db/src/collection.ts b/packages/db/src/collection.ts index c2b543717d..59e2ad56c2 100644 --- a/packages/db/src/collection.ts +++ b/packages/db/src/collection.ts @@ -277,8 +277,8 @@ export class CollectionImpl< throw new Error(`Collection requires a sync config`) } - this.transactions = new SortedMap>( - (a, b) => a.createdAt.getTime() - b.createdAt.getTime() + this.transactions = new SortedMap>((a, b) => + a.compareCreatedAt(b) ) this.config = config diff --git a/packages/db/src/transactions.ts b/packages/db/src/transactions.ts index 024c4a19bf..8e570b1282 100644 --- a/packages/db/src/transactions.ts +++ b/packages/db/src/transactions.ts @@ -12,6 +12,8 @@ import type { const transactions: Array> = [] let transactionStack: Array> = [] +let sequenceNumber = 0 + export function createTransaction< TData extends object = Record, >(config: TransactionConfig): Transaction { @@ -54,6 +56,7 @@ export class Transaction< public isPersisted: Deferred> public autoCommit: boolean public createdAt: Date + public sequenceNumber: number public metadata: Record public error?: { message: string @@ -71,6 +74,7 @@ export class Transaction< this.isPersisted = createDeferred>() this.autoCommit = config.autoCommit ?? true this.createdAt = new Date() + this.sequenceNumber = sequenceNumber++ this.metadata = config.metadata ?? {} } @@ -200,4 +204,19 @@ export class Transaction< return this } + + /** + * Compare two transactions by their createdAt time and sequence number in order + * to sort them in the order they were created. + * @param other - The other transaction to compare to + * @returns -1 if this transaction was created before the other, 1 if it was created after, 0 if they were created at the same time + */ + compareCreatedAt(other: Transaction): number { + const createdAtComparison = + this.createdAt.getTime() - other.createdAt.getTime() + if (createdAtComparison !== 0) { + return createdAtComparison + } + return this.sequenceNumber - other.sequenceNumber + } } From 7b2d15b9ace71b1a8b01c09d26f50f9040de7a87 Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Wed, 25 Jun 2025 08:11:42 +0000 Subject: [PATCH 3/4] Add local-only collection with optimistic in-memory sync support Implement true loopback sync for local-only collections Add initial data support for local-only collections Refactor local-only collection with optimistic updates and custom callbacks Checkpoint before follow-up message Update local-only sync to support custom key types Update local-only collection tests with extended generic types Refactor local-only sync function signature for improved readability Add explicit key type parameter to localOnlyCollectionOptions Checkpoint before follow-up message Checkpoint before follow-up message Add localOnly collection type for in-memory collections Add localOnly collection type for in-memory collections Refactor local-only collection handlers to call user handlers before confirming transactions fix changeset --- .changeset/local-only-collection.md | 5 + packages/db-collections/src/index.ts | 5 + packages/db-collections/src/local-only.ts | 228 +++++++++ .../db-collections/tests/local-only.test-d.ts | 137 ++++++ .../db-collections/tests/local-only.test.ts | 438 ++++++++++++++++++ 5 files changed, 813 insertions(+) create mode 100644 .changeset/local-only-collection.md create mode 100644 packages/db-collections/src/local-only.ts create mode 100644 packages/db-collections/tests/local-only.test-d.ts create mode 100644 packages/db-collections/tests/local-only.test.ts diff --git a/.changeset/local-only-collection.md b/.changeset/local-only-collection.md new file mode 100644 index 0000000000..6be0b1184b --- /dev/null +++ b/.changeset/local-only-collection.md @@ -0,0 +1,5 @@ +--- +"@tanstack/db-collections": patch +--- + +Add localOnly collection type for in-memory collections with loopback sync. diff --git a/packages/db-collections/src/index.ts b/packages/db-collections/src/index.ts index 7736320db8..c1790506d6 100644 --- a/packages/db-collections/src/index.ts +++ b/packages/db-collections/src/index.ts @@ -15,3 +15,8 @@ export { type StorageApi, type StorageEventApi, } from "./local-storage" +export { + localOnlyCollectionOptions, + type LocalOnlyCollectionConfig, + type LocalOnlyCollectionUtils, +} from "./local-only" diff --git a/packages/db-collections/src/local-only.ts b/packages/db-collections/src/local-only.ts new file mode 100644 index 0000000000..64ac7c231a --- /dev/null +++ b/packages/db-collections/src/local-only.ts @@ -0,0 +1,228 @@ +import type { + DeleteMutationFnParams, + InsertMutationFnParams, + OperationType, + ResolveType, + SyncConfig, + UpdateMutationFnParams, + UtilsRecord, +} from "@tanstack/db" +import type { StandardSchemaV1 } from "@standard-schema/spec" + +/** + * Configuration interface for Local-only collection options + * @template TExplicit - The explicit type of items in the collection (highest priority) + * @template TSchema - The schema type for validation and type inference (second priority) + * @template TFallback - The fallback type if no explicit or schema type is provided + * @template TKey - The type of the key returned by getKey + * + * @remarks + * Type resolution follows a priority order: + * 1. If you provide an explicit type via generic parameter, it will be used + * 2. If no explicit type is provided but a schema is, the schema's output type will be inferred + * 3. If neither explicit type nor schema is provided, the fallback type will be used + * + * You should provide EITHER an explicit type OR a schema, but not both, as they would conflict. + */ +export interface LocalOnlyCollectionConfig< + TExplicit = unknown, + TSchema extends StandardSchemaV1 = never, + TFallback extends Record = Record, + TKey extends string | number = string | number, +> { + /** + * Standard Collection configuration properties + */ + id?: string + schema?: TSchema + getKey: (item: ResolveType) => TKey + + /** + * Optional initial data to populate the collection with on creation + * This data will be applied during the initial sync process + */ + initialData?: Array> + + /** + * Optional asynchronous handler function called after an insert operation + * @param params Object containing transaction and mutation information + * @returns Promise resolving to any value + */ + onInsert?: ( + params: InsertMutationFnParams> + ) => Promise + + /** + * Optional asynchronous handler function called after an update operation + * @param params Object containing transaction and mutation information + * @returns Promise resolving to any value + */ + onUpdate?: ( + params: UpdateMutationFnParams> + ) => Promise + + /** + * Optional asynchronous handler function called after a delete operation + * @param params Object containing transaction and mutation information + * @returns Promise resolving to any value + */ + onDelete?: ( + params: DeleteMutationFnParams> + ) => Promise +} + +/** + * Local-only collection utilities type (currently empty but matches the pattern) + */ +export interface LocalOnlyCollectionUtils extends UtilsRecord {} + +/** + * Creates Local-only collection options for use with a standard Collection + * This is an in-memory collection that doesn't sync but uses a loopback sync config + * that immediately "syncs" all optimistic changes to the collection. + * + * @template TExplicit - The explicit type of items in the collection (highest priority) + * @template TSchema - The schema type for validation and type inference (second priority) + * @template TFallback - The fallback type if no explicit or schema type is provided + * @template TKey - The type of the key returned by getKey + * @param config - Configuration options for the Local-only collection + * @returns Collection options with utilities + */ +export function localOnlyCollectionOptions< + TExplicit = unknown, + TSchema extends StandardSchemaV1 = never, + TFallback extends Record = Record, + TKey extends string | number = string | number, +>(config: LocalOnlyCollectionConfig) { + type ResolvedType = ResolveType + + const { initialData, onInsert, onUpdate, onDelete, ...restConfig } = config + + // Create the sync configuration with transaction confirmation capability + const syncResult = createLocalOnlySync(initialData) + + // Create wrapper handlers that call user handlers first, then confirm transactions + const wrappedOnInsert = async ( + params: InsertMutationFnParams + ) => { + // Call user handler first if provided + let handlerResult + if (onInsert) { + handlerResult = (await onInsert(params)) ?? {} + } + + // Then synchronously confirm the transaction by looping through mutations + syncResult.confirmOperationsSync(params.transaction.mutations) + + return handlerResult + } + + const wrappedOnUpdate = async ( + params: UpdateMutationFnParams + ) => { + // Call user handler first if provided + let handlerResult + if (onUpdate) { + handlerResult = (await onUpdate(params)) ?? {} + } + + // Then synchronously confirm the transaction by looping through mutations + syncResult.confirmOperationsSync(params.transaction.mutations) + + return handlerResult + } + + const wrappedOnDelete = async ( + params: DeleteMutationFnParams + ) => { + // Call user handler first if provided + let handlerResult + if (onDelete) { + handlerResult = (await onDelete(params)) ?? {} + } + + // Then synchronously confirm the transaction by looping through mutations + syncResult.confirmOperationsSync(params.transaction.mutations) + + return handlerResult + } + + return { + ...restConfig, + sync: syncResult.sync, + onInsert: wrappedOnInsert, + onUpdate: wrappedOnUpdate, + onDelete: wrappedOnDelete, + utils: {} as LocalOnlyCollectionUtils, + startSync: true, + gcTime: 0, + } +} + +/** + * Internal function to create Local-only sync configuration with transaction confirmation + * This captures the sync functions and provides synchronous confirmation of operations + */ +function createLocalOnlySync( + initialData?: Array +) { + // Capture sync functions for transaction confirmation + let syncBegin: (() => void) | null = null + let syncWrite: ((message: { type: OperationType; value: T }) => void) | null = + null + let syncCommit: (() => void) | null = null + + const sync: SyncConfig = { + sync: (params) => { + const { begin, write, commit } = params + + // Capture sync functions for later use by confirmOperationsSync + syncBegin = begin + syncWrite = write + syncCommit = commit + + // Apply initial data if provided + if (initialData && initialData.length > 0) { + begin() + initialData.forEach((item) => { + write({ + type: `insert`, + value: item, + }) + }) + commit() + } + + // Return empty unsubscribe function - no ongoing sync needed + return () => {} + }, + getSyncMetadata: () => ({}), + } + + /** + * Synchronously confirms optimistic operations by immediately writing through sync + * This loops through transaction mutations and applies them to move from optimistic to synced state + */ + const confirmOperationsSync = (mutations: Array) => { + if (!syncBegin || !syncWrite || !syncCommit) { + return // Sync not initialized yet, which is fine + } + + // Immediately write back through sync interface + syncBegin() + mutations.forEach((mutation) => { + if (syncWrite) { + syncWrite({ + type: mutation.type, + value: mutation.modified, + }) + } + }) + syncCommit() + } + + return { + sync, + confirmOperationsSync, + } +} diff --git a/packages/db-collections/tests/local-only.test-d.ts b/packages/db-collections/tests/local-only.test-d.ts new file mode 100644 index 0000000000..c8a668b52c --- /dev/null +++ b/packages/db-collections/tests/local-only.test-d.ts @@ -0,0 +1,137 @@ +import { describe, expectTypeOf, it } from "vitest" +import { createCollection } from "@tanstack/db" +import { localOnlyCollectionOptions } from "../src/local-only" +import type { LocalOnlyCollectionUtils } from "../src/local-only" +import type { Collection } from "@tanstack/db" + +interface TestItem extends Record { + id: number + name: string + completed?: boolean +} + +describe(`LocalOnly Collection Types`, () => { + it(`should have correct return type from localOnlyCollectionOptions`, () => { + const config = { + id: `test-local-only`, + getKey: (item: TestItem) => item.id, + } + + const options = localOnlyCollectionOptions< + TestItem, + never, + TestItem, + number + >(config) + + // Test that options has the expected structure + expectTypeOf(options).toHaveProperty(`sync`) + expectTypeOf(options).toHaveProperty(`onInsert`) + expectTypeOf(options).toHaveProperty(`onUpdate`) + expectTypeOf(options).toHaveProperty(`onDelete`) + expectTypeOf(options).toHaveProperty(`utils`) + expectTypeOf(options).toHaveProperty(`getKey`) + + // Test that getKey returns the correct type + expectTypeOf(options.getKey).toMatchTypeOf<(item: TestItem) => number>() + }) + + it(`should be compatible with createCollection`, () => { + const config = { + id: `test-local-only`, + getKey: (item: TestItem) => item.id, + } + + const options = localOnlyCollectionOptions< + TestItem, + never, + TestItem, + number + >(config) + + const collection = createCollection< + TestItem, + number, + LocalOnlyCollectionUtils + >(options) + + // Test that the collection has the expected type + expectTypeOf(collection).toMatchTypeOf< + Collection + >() + }) + + it(`should work with custom callbacks`, () => { + const configWithCallbacks = { + id: `test-with-callbacks`, + getKey: (item: TestItem) => item.id, + onInsert: () => Promise.resolve({}), + onUpdate: () => Promise.resolve({}), + onDelete: () => Promise.resolve({}), + } + + const options = localOnlyCollectionOptions< + TestItem, + never, + TestItem, + number + >(configWithCallbacks) + const collection = createCollection< + TestItem, + number, + LocalOnlyCollectionUtils + >(options) + + expectTypeOf(collection).toMatchTypeOf< + Collection + >() + }) + + it(`should work with initial data`, () => { + const configWithInitialData = { + id: `test-with-initial-data`, + getKey: (item: TestItem) => item.id, + initialData: [{ id: 1, name: `Test` }] as Array, + } + + const options = localOnlyCollectionOptions< + TestItem, + never, + TestItem, + number + >(configWithInitialData) + const collection = createCollection< + TestItem, + number, + LocalOnlyCollectionUtils + >(options) + + expectTypeOf(collection).toMatchTypeOf< + Collection + >() + }) + + it(`should infer key type from getKey function`, () => { + const config = { + id: `test-string-key`, + getKey: (item: TestItem) => `item-${item.id}`, + } + + const options = localOnlyCollectionOptions< + TestItem, + never, + TestItem, + string + >(config) + const collection = createCollection< + TestItem, + string, + LocalOnlyCollectionUtils + >(options) + + expectTypeOf(collection).toMatchTypeOf< + Collection + >() + expectTypeOf(options.getKey).toMatchTypeOf<(item: TestItem) => string>() + }) +}) diff --git a/packages/db-collections/tests/local-only.test.ts b/packages/db-collections/tests/local-only.test.ts new file mode 100644 index 0000000000..862b8352da --- /dev/null +++ b/packages/db-collections/tests/local-only.test.ts @@ -0,0 +1,438 @@ +import { beforeEach, describe, expect, it, vi } from "vitest" +import { createCollection } from "@tanstack/db" +import { localOnlyCollectionOptions } from "../src/local-only" +import type { LocalOnlyCollectionUtils } from "../src/local-only" +import type { Collection } from "@tanstack/db" + +interface TestItem extends Record { + id: number + name: string + completed?: boolean +} + +describe(`LocalOnly Collection`, () => { + let collection: Collection + + beforeEach(() => { + // Create collection with LocalOnly configuration + collection = createCollection( + localOnlyCollectionOptions({ + id: `test-local-only`, + getKey: (item: TestItem) => item.id, + }) + ) + }) + + it(`should create an empty collection initially`, () => { + expect(collection.state).toEqual(new Map()) + expect(collection.size).toBe(0) + }) + + it(`should handle insert operations optimistically`, () => { + // Insert an item + collection.insert({ id: 1, name: `Test Item` }) + + // The item should be immediately available in the collection + expect(collection.has(1)).toBe(true) + expect(collection.get(1)).toEqual({ id: 1, name: `Test Item` }) + expect(collection.size).toBe(1) + }) + + it(`should handle multiple inserts`, () => { + // Insert multiple items + collection.insert([ + { id: 1, name: `Item 1` }, + { id: 2, name: `Item 2` }, + { id: 3, name: `Item 3` }, + ]) + + // All items should be immediately available + expect(collection.size).toBe(3) + expect(collection.get(1)).toEqual({ id: 1, name: `Item 1` }) + expect(collection.get(2)).toEqual({ id: 2, name: `Item 2` }) + expect(collection.get(3)).toEqual({ id: 3, name: `Item 3` }) + }) + + it(`should handle update operations optimistically`, () => { + // Insert an item first + collection.insert({ id: 1, name: `Original Item` }) + + // Update the item + collection.update(1, (draft) => { + draft.name = `Updated Item` + draft.completed = true + }) + + // The update should be immediately reflected + expect(collection.get(1)).toEqual({ + id: 1, + name: `Updated Item`, + completed: true, + }) + }) + + it(`should handle delete operations optimistically`, () => { + // Insert items first + collection.insert([ + { id: 1, name: `Item 1` }, + { id: 2, name: `Item 2` }, + ]) + + expect(collection.size).toBe(2) + + // Delete one item + collection.delete(1) + + // The item should be immediately removed + expect(collection.has(1)).toBe(false) + expect(collection.has(2)).toBe(true) + expect(collection.size).toBe(1) + }) + + it(`should handle mixed operations`, () => { + // Perform a series of mixed operations + collection.insert({ id: 1, name: `Item 1` }) + collection.insert({ id: 2, name: `Item 2` }) + + expect(collection.size).toBe(2) + + // Update item 1 + collection.update(1, (draft) => { + draft.completed = true + }) + + // Delete item 2 + collection.delete(2) + + // Insert item 3 + collection.insert({ id: 3, name: `Item 3` }) + + // Check final state + expect(collection.size).toBe(2) + expect(collection.get(1)).toEqual({ + id: 1, + name: `Item 1`, + completed: true, + }) + expect(collection.has(2)).toBe(false) + expect(collection.get(3)).toEqual({ id: 3, name: `Item 3` }) + }) + + it(`should support change subscriptions`, () => { + const changeHandler = vi.fn() + + // Subscribe to changes + const unsubscribe = collection.subscribeChanges(changeHandler) + + // Insert an item + collection.insert({ id: 1, name: `Test Item` }) + + // The change handler should have been called + expect(changeHandler).toHaveBeenCalledTimes(1) + expect(changeHandler).toHaveBeenCalledWith([ + { + type: `insert`, + key: 1, + value: { id: 1, name: `Test Item` }, + }, + ]) + + // Clean up + unsubscribe() + }) + + it(`should support toArray method`, () => { + // Insert some items + collection.insert([ + { id: 3, name: `Item 3` }, + { id: 1, name: `Item 1` }, + { id: 2, name: `Item 2` }, + ]) + + const array = collection.toArray + + // Should contain all items + expect(array).toHaveLength(3) + expect(array).toEqual( + expect.arrayContaining([ + { id: 1, name: `Item 1` }, + { id: 2, name: `Item 2` }, + { id: 3, name: `Item 3` }, + ]) + ) + }) + + it(`should support entries and iteration`, () => { + // Insert some items + collection.insert([ + { id: 1, name: `Item 1` }, + { id: 2, name: `Item 2` }, + ]) + + // Test entries + const entries = Array.from(collection.entries()) + expect(entries).toHaveLength(2) + expect(entries).toEqual( + expect.arrayContaining([ + [1, { id: 1, name: `Item 1` }], + [2, { id: 2, name: `Item 2` }], + ]) + ) + + // Test values iteration + const items = [] + for (const item of collection.values()) { + items.push(item) + } + expect(items).toHaveLength(2) + }) + + describe(`Pure optimistic behavior`, () => { + it(`should handle insert operations optimistically`, () => { + // Insert an item - this works purely optimistically + collection.insert({ id: 1, name: `Test Item` }) + + // The item should be available in the collection + expect(collection.has(1)).toBe(true) + expect(collection.get(1)).toEqual({ id: 1, name: `Test Item` }) + }) + + it(`should handle update operations optimistically`, () => { + // Insert an item first + collection.insert({ id: 1, name: `Test Item` }) + + // Update the item - this works purely optimistically + collection.update(1, (draft) => { + draft.name = `Updated Item` + }) + + // The update should be reflected in the collection + expect(collection.get(1)).toEqual({ id: 1, name: `Updated Item` }) + }) + + it(`should handle delete operations optimistically`, () => { + // Insert an item first + collection.insert({ id: 1, name: `Test Item` }) + expect(collection.has(1)).toBe(true) + + // Delete the item - this works purely optimistically + collection.delete(1) + + // The item should be removed from the collection + expect(collection.has(1)).toBe(false) + }) + }) + + describe(`Schema support`, () => { + it(`should work with schema configuration`, () => { + // This tests that the type system works correctly with schemas + // In a real implementation, you would provide a schema for validation + const testCollection = createCollection( + localOnlyCollectionOptions({ + id: `test-schema`, + getKey: (item: TestItem) => item.id, + }) + ) + + // Basic operations should still work + testCollection.insert({ id: 1, name: `Test with Schema` }) + expect(testCollection.get(1)).toEqual({ id: 1, name: `Test with Schema` }) + }) + }) + + describe(`Utils object`, () => { + it(`should expose utils object (even if empty)`, () => { + expect(collection.utils).toBeDefined() + expect(typeof collection.utils).toBe(`object`) + }) + }) + + describe(`Custom callbacks`, () => { + it(`should call custom onInsert callback when provided`, () => { + const onInsertSpy = vi.fn() + + const testCollection = createCollection( + localOnlyCollectionOptions({ + id: `test-custom-callbacks`, + getKey: (item: TestItem) => item.id, + onInsert: onInsertSpy, + }) + ) + + testCollection.insert({ id: 1, name: `Test Item` }) + + expect(onInsertSpy).toHaveBeenCalledTimes(1) + expect(onInsertSpy).toHaveBeenCalledWith( + expect.objectContaining({ + transaction: expect.objectContaining({ + mutations: expect.arrayContaining([ + expect.objectContaining({ + type: `insert`, + modified: { id: 1, name: `Test Item` }, + }), + ]), + }), + }) + ) + + // Collection should still work normally + expect(testCollection.get(1)).toEqual({ id: 1, name: `Test Item` }) + }) + + it(`should call custom onUpdate callback when provided`, () => { + const onUpdateSpy = vi.fn() + + const testCollection = createCollection( + localOnlyCollectionOptions({ + id: `test-custom-update`, + getKey: (item: TestItem) => item.id, + onUpdate: onUpdateSpy, + }) + ) + + testCollection.insert({ id: 1, name: `Test Item` }) + testCollection.update(1, (draft) => { + draft.name = `Updated Item` + }) + + expect(onUpdateSpy).toHaveBeenCalledTimes(1) + expect(onUpdateSpy).toHaveBeenCalledWith( + expect.objectContaining({ + transaction: expect.objectContaining({ + mutations: expect.arrayContaining([ + expect.objectContaining({ + type: `update`, + modified: { id: 1, name: `Updated Item` }, + }), + ]), + }), + }) + ) + + // Collection should still work normally + expect(testCollection.get(1)).toEqual({ id: 1, name: `Updated Item` }) + }) + + it(`should call custom onDelete callback when provided`, () => { + const onDeleteSpy = vi.fn() + + const testCollection = createCollection( + localOnlyCollectionOptions({ + id: `test-custom-delete`, + getKey: (item: TestItem) => item.id, + onDelete: onDeleteSpy, + }) + ) + + testCollection.insert({ id: 1, name: `Test Item` }) + testCollection.delete(1) + + expect(onDeleteSpy).toHaveBeenCalledTimes(1) + expect(onDeleteSpy).toHaveBeenCalledWith( + expect.objectContaining({ + transaction: expect.objectContaining({ + mutations: expect.arrayContaining([ + expect.objectContaining({ + type: `delete`, + original: { id: 1, name: `Test Item` }, + }), + ]), + }), + }) + ) + + // Collection should still work normally + expect(testCollection.has(1)).toBe(false) + }) + + it(`should work without custom callbacks`, () => { + const testCollection = createCollection( + localOnlyCollectionOptions({ + id: `test-no-callbacks`, + getKey: (item: TestItem) => item.id, + }) + ) + + // Should work normally without callbacks + testCollection.insert({ id: 1, name: `Test Item` }) + testCollection.update(1, (draft) => { + draft.name = `Updated Item` + }) + testCollection.delete(1) + + expect(testCollection.has(1)).toBe(false) + }) + }) + + describe(`Initial data`, () => { + it(`should populate collection with initial data on creation`, () => { + const initialItems: Array = [ + { id: 10, name: `Initial Item 1` }, + { id: 20, name: `Initial Item 2` }, + { id: 30, name: `Initial Item 3` }, + ] + + const testCollection = createCollection( + localOnlyCollectionOptions({ + id: `test-initial-data`, + getKey: (item: TestItem) => item.id, + initialData: initialItems, + }) + ) + + // Collection should be populated with initial data + expect(testCollection.size).toBe(3) + expect(testCollection.get(10)).toEqual({ id: 10, name: `Initial Item 1` }) + expect(testCollection.get(20)).toEqual({ id: 20, name: `Initial Item 2` }) + expect(testCollection.get(30)).toEqual({ id: 30, name: `Initial Item 3` }) + }) + + it(`should work with empty initial data array`, () => { + const testCollection = createCollection( + localOnlyCollectionOptions({ + id: `test-empty-initial-data`, + getKey: (item: TestItem) => item.id, + initialData: [], + }) + ) + + // Collection should be empty + expect(testCollection.size).toBe(0) + }) + + it(`should work without initial data property`, () => { + const testCollection = createCollection( + localOnlyCollectionOptions({ + id: `test-no-initial-data`, + getKey: (item: TestItem) => item.id, + }) + ) + + // Collection should be empty + expect(testCollection.size).toBe(0) + }) + + it(`should allow adding more items after initial data`, () => { + const initialItems: Array = [{ id: 100, name: `Initial Item` }] + + const testCollection = createCollection( + localOnlyCollectionOptions({ + id: `test-initial-plus-more`, + getKey: (item: TestItem) => item.id, + initialData: initialItems, + }) + ) + + // Should start with initial data + expect(testCollection.size).toBe(1) + expect(testCollection.get(100)).toEqual({ id: 100, name: `Initial Item` }) + + // Should be able to add more items + testCollection.insert({ id: 200, name: `Added Item` }) + + expect(testCollection.size).toBe(2) + expect(testCollection.get(100)).toEqual({ id: 100, name: `Initial Item` }) + expect(testCollection.get(200)).toEqual({ id: 200, name: `Added Item` }) + }) + }) +}) From 72c3e172587cc36605a25e49c158fe4bbc1918bf Mon Sep 17 00:00:00 2001 From: Sam Willis Date: Sun, 6 Jul 2025 15:20:55 +0100 Subject: [PATCH 4/4] docs --- docs/overview.md | 52 +++++++++++++++++++++++++++++++++++++++++++++--- 1 file changed, 49 insertions(+), 3 deletions(-) diff --git a/docs/overview.md b/docs/overview.md index 536ac068d9..97529708e5 100644 --- a/docs/overview.md +++ b/docs/overview.md @@ -154,7 +154,7 @@ There are a number of built-in collection types implemented in [`@tanstack/db-co 1. [`QueryCollection`](#querycollection) to load data into collections using [TanStack Query](https://tanstack.com/query) 2. [`ElectricCollection`](#electriccollection) to sync data into collections using [ElectricSQL](https://electric-sql.com) 3. [`LocalStorageCollection`](#localstoragecollection) for small amounts of local-only state that syncs across browser tabs -4. [WIP] [`LocalOnlyCollection`](#localonlycollection) for in-memory client data or UI state +4. [`LocalOnlyCollection`](#localonlycollection) for in-memory client data or UI state You can also use: @@ -287,9 +287,55 @@ export const sessionCollection = createCollection(localStorageCollectionOptions( #### `LocalOnlyCollection` -This is WIP. Track progress at [#79](https://github.com/TanStack/db/issues/79). +LocalOnly collections are designed for in-memory client data or UI state that doesn't need to persist across browser sessions or sync across tabs. They provide a simple way to manage temporary, session-only data with full optimistic mutation support. -LocalOnly collections will be designed for in-memory client data or UI state that doesn't need to persist across browser sessions or sync across tabs. +Use `localOnlyCollectionOptions` to create a collection that stores data only in memory: + +```ts +import { createCollection } from '@tanstack/react-db' +import { localOnlyCollectionOptions } from '@tanstack/db-collections' + +export const uiStateCollection = createCollection(localOnlyCollectionOptions({ + id: 'ui-state', + getKey: (item) => item.id, + schema: uiStateSchema, + // Optional initial data to populate the collection + initialData: [ + { id: 'sidebar', isOpen: false }, + { id: 'theme', mode: 'light' } + ] +})) +``` + +The LocalOnly collection requires: + +- `getKey` — identifies the id for items in the collection + +Optional configuration: + +- `initialData` — array of items to populate the collection with on creation +- `onInsert`, `onUpdate`, `onDelete` — optional mutation handlers for custom logic + +Mutation handlers are completely optional. When provided, they are called before the optimistic state is confirmed. The collection automatically manages the transition from optimistic to confirmed state internally. + +```ts +export const tempDataCollection = createCollection(localOnlyCollectionOptions({ + id: 'temp-data', + getKey: (item) => item.id, + onInsert: async ({ transaction }) => { + // Custom logic before confirming the insert + console.log('Inserting:', transaction.mutations[0].modified) + }, + onUpdate: async ({ transaction }) => { + // Custom logic before confirming the update + const { original, modified } = transaction.mutations[0] + console.log('Updating from', original, 'to', modified) + } +})) +``` + +> [!TIP] +> LocalOnly collections are perfect for temporary UI state, form data, or any client-side data that doesn't need persistence. For data that should persist across sessions, use [`LocalStorageCollection`](#localstoragecollection) instead. #### Derived collections