Skip to content

Commit 0294a7e

Browse files
authored
fix: prevent adding duplicates on created events (#70)
1 parent 2963c7e commit 0294a7e

File tree

2 files changed

+37
-3
lines changed

2 files changed

+37
-3
lines changed

src/useFind.ts

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -13,13 +13,18 @@ function loadServiceEventHandlers<
1313
params: Ref<Params | undefined | null>,
1414
data: Ref<M[]>,
1515
): () => void {
16-
const onCreated = (item: M): void => {
16+
const onCreated = (createdItem: M): void => {
1717
// ignore items not matching the query or when no params are set
18-
if (!params.value || !sift(params.value.query)(item)) {
18+
if (!params.value || !sift(params.value.query)(createdItem)) {
1919
return;
2020
}
2121

22-
data.value = [...data.value, item];
22+
// ignore items that already exist
23+
if (data.value.find((item) => getId(createdItem) === getId(item)) !== undefined) {
24+
return;
25+
}
26+
27+
data.value = [...data.value, createdItem];
2328
};
2429

2530
const onRemoved = (item: M): void => {

test/useFind.test.ts

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -427,6 +427,35 @@ describe('Find composition', () => {
427427
expect(findComposition && findComposition.data.value).not.toContainEqual(additionalTestModel);
428428
});
429429

430+
it('should ignore "create" events when item already exists', async () => {
431+
expect.assertions(2);
432+
433+
// given
434+
const emitter = eventHelper();
435+
const feathersMock = {
436+
service: () => ({
437+
find: jest.fn(() => [additionalTestModel]),
438+
on: emitter.on,
439+
off: jest.fn(),
440+
}),
441+
on: jest.fn(),
442+
off: jest.fn(),
443+
} as unknown as Application;
444+
const useFind = useFindOriginal(feathersMock);
445+
let findComposition = null as UseFind<TestModel> | null;
446+
mountComposition(() => {
447+
findComposition = useFind('testModels');
448+
});
449+
await nextTick();
450+
451+
// when
452+
emitter.emit('created', additionalTestModel);
453+
454+
// then
455+
expect(findComposition).toBeTruthy();
456+
expect(findComposition && findComposition.data.value).toHaveLength(1);
457+
});
458+
430459
it('should listen to "patch" events', async () => {
431460
expect.assertions(2);
432461

0 commit comments

Comments
 (0)