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
6 changes: 6 additions & 0 deletions .changeset/fix-solid-custom-key-reconciliation.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
---
'@tanstack/solid-db': patch
---

Keep Solid live-query rows tied to their result identities when custom-key rows
reorder or multiple results share the same public `$key`.
44 changes: 40 additions & 4 deletions packages/solid-db/src/useLiveQuery.ts
Original file line number Diff line number Diff line change
Expand Up @@ -329,7 +329,14 @@ export function useLiveQuery(
// Reactive state that gets updated granularly through change events
const state = new ReactiveMap<string | number, any>()

// Reactive data array that maintains sorted order
// Keep the live Collection's result keys private while preserving one stable
// Solid store per logical row. A row's public $key can belong to an upstream
// Collection and is therefore not necessarily unique in this result.
const rowsByKey = new Map<
string | number,
{ value: any; update: (value: any) => void }
Comment thread
coderabbitai[bot] marked this conversation as resolved.
>()
let rowsCollection: Collection<any, any, any> | undefined
const [data, setData] = createStore<Array<any>>([], {
name: `TanstackDBData`,
})
Expand All @@ -346,9 +353,31 @@ export function useLiveQuery(
const syncDataFromCollection = (
currentCollection: Collection<any, any, any>,
) => {
setData((prev) =>
reconcile(Array.from(currentCollection.values()))(prev).filter(Boolean),
)
const nextRows: Array<any> = []
const retainedKeys = new Set<string | number>()

for (const [key, value] of currentCollection.entries()) {
retainedKeys.add(key)

const existing = rowsByKey.get(key)
if (existing) {
existing.update(value)
nextRows.push(existing.value)
} else {
const [row, setRow] = createStore(value)
rowsByKey.set(key, {
value: row,
update: (nextValue) => setRow(reconcile(nextValue, { key: null })),
})
nextRows.push(row)
}
}

for (const key of rowsByKey.keys()) {
if (!retainedKeys.has(key)) rowsByKey.delete(key)
}

setData((previous) => reconcile(nextRows, { key: null })(previous))
}

// Generation guard for the resource's async continuations: Solid discards a
Expand Down Expand Up @@ -397,10 +426,17 @@ export function useLiveQuery(
if (!currentCollection) {
setStatus(`disabled` as const)
state.clear()
rowsByKey.clear()
rowsCollection = undefined
setData([])
return
}

if (rowsCollection !== currentCollection) {
rowsByKey.clear()
rowsCollection = currentCollection
}

// The shared observer owns subscription, the ready-race, and status; Solid
// materializes into its keyed ReactiveMap (granular) + reconciled store.
const observer = createLiveQueryObserver(currentCollection)
Expand Down
Loading
Loading