Skip to content

Commit 6ebfea0

Browse files
committed
feat: allow specifying custom items merger for AutoFetchCollection
1 parent 9c28aa6 commit 6ebfea0

File tree

2 files changed

+8
-1
lines changed

2 files changed

+8
-1
lines changed

docs/replication/index.md

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -110,6 +110,10 @@ const Todos = new AutoFetchCollection({
110110
// If a persistence adapter is used, the data is loaded first and will be updated after the server data is fetched
111111
// If the data will be updated, the data will be saved to the persistence adapter and pushed to the server simultaneously
112112
persistence: createLocalStorageAdapter('todos'),
113+
114+
// Optionally you can also specify a mergeItems function to merge items
115+
// if they're returned by multiple fetchQueryItems calls.
116+
mergeItems: (itemA, itemB) => ({ ...itemA, ...itemB }),
113117
})
114118

115119
// You can also observe the loading state of the collection.

packages/signaldb/src/AutoFetchCollection.ts

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ interface AutoFetchOptions<T extends { id: I } & Record<string, any>, I> {
1010
fetchQueryItems: (selector: Selector<T>) => ReturnType<ReplicatedCollectionOptions<T, I>['pull']>,
1111
purgeDelay?: number,
1212
registerRemoteChange?: (onChange: () => Promise<void>) => Promise<void>,
13+
mergeItems?: (itemA: T, itemB: T) => T,
1314
}
1415
export type AutoFetchCollectionOptions<
1516
T extends BaseItem<I>,
@@ -35,6 +36,7 @@ export default class AutoFetchCollection<
3536
private reactivityAdapter: ReactivityAdapter | null = null
3637
private loadingSignals = new Map<string, Signal<boolean>>()
3738
private isFetchingSignal: Signal<boolean>
39+
private mergeItems: (itemA: T, itemB: T) => T
3840

3941
/**
4042
* @param options {Object} - Options for the collection.
@@ -54,7 +56,7 @@ export default class AutoFetchCollection<
5456
newItems.push(item)
5557
return
5658
}
57-
newItems[index] = { ...newItems[index], ...item }
59+
newItems[index] = this.mergeItems(newItems[index], item)
5860
})
5961
return newItems
6062
}, []),
@@ -64,6 +66,7 @@ export default class AutoFetchCollection<
6466
return Promise.resolve()
6567
},
6668
})
69+
this.mergeItems = options.mergeItems ?? ((itemA, itemB) => ({ ...itemA, ...itemB }))
6770
this.purgeDelay = options.purgeDelay ?? 10000 // 10 seconds
6871
this.isFetchingSignal = createSignal(options.reactivity?.create(), false)
6972
if (!triggerRemoteChange) throw new Error('No triggerRemoteChange method found. Looks like your persistence adapter was not registered')

0 commit comments

Comments
 (0)