Skip to content
Merged
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
5 changes: 5 additions & 0 deletions .changeset/khaki-cougars-give.md
Original file line number Diff line number Diff line change
@@ -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
5 changes: 5 additions & 0 deletions .changeset/local-only-collection.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@tanstack/db-collections": patch
---

Add localOnly collection type for in-memory collections with loopback sync.
5 changes: 5 additions & 0 deletions .changeset/open-foxes-say.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@tanstack/db": patch
---

Ensure that all transactions are given an id, fixes a potential bug with direct mutations
52 changes: 49 additions & 3 deletions docs/overview.md
Original file line number Diff line number Diff line change
Expand Up @@ -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:

Expand Down Expand Up @@ -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

Expand Down
5 changes: 5 additions & 0 deletions packages/db-collections/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,3 +15,8 @@ export {
type StorageApi,
type StorageEventApi,
} from "./local-storage"
export {
localOnlyCollectionOptions,
type LocalOnlyCollectionConfig,
type LocalOnlyCollectionUtils,
} from "./local-only"
228 changes: 228 additions & 0 deletions packages/db-collections/src/local-only.ts
Original file line number Diff line number Diff line change
@@ -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<string, unknown> = Record<string, unknown>,
TKey extends string | number = string | number,
> {
/**
* Standard Collection configuration properties
*/
id?: string
schema?: TSchema
getKey: (item: ResolveType<TExplicit, TSchema, TFallback>) => TKey

/**
* Optional initial data to populate the collection with on creation
* This data will be applied during the initial sync process
*/
initialData?: Array<ResolveType<TExplicit, TSchema, TFallback>>

/**
* 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<ResolveType<TExplicit, TSchema, TFallback>>
) => Promise<any>

/**
* 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<ResolveType<TExplicit, TSchema, TFallback>>
) => Promise<any>

/**
* 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<ResolveType<TExplicit, TSchema, TFallback>>
) => Promise<any>
}

/**
* 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<string, unknown> = Record<string, unknown>,
TKey extends string | number = string | number,
>(config: LocalOnlyCollectionConfig<TExplicit, TSchema, TFallback, TKey>) {
type ResolvedType = ResolveType<TExplicit, TSchema, TFallback>

const { initialData, onInsert, onUpdate, onDelete, ...restConfig } = config

// Create the sync configuration with transaction confirmation capability
const syncResult = createLocalOnlySync<ResolvedType, TKey>(initialData)

// Create wrapper handlers that call user handlers first, then confirm transactions
const wrappedOnInsert = async (
params: InsertMutationFnParams<ResolvedType>
) => {
// 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<ResolvedType>
) => {
// 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<ResolvedType>
) => {
// 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<T extends object, TKey extends string | number>(
initialData?: Array<T>
) {
// 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<T, TKey> = {
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<any>) => {
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,
}
}
Loading