Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: prevent adding duplicates on created events #70

Merged
merged 1 commit into from
Mar 25, 2022
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
11 changes: 8 additions & 3 deletions src/useFind.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,13 +13,18 @@ function loadServiceEventHandlers<
params: Ref<Params | undefined | null>,
data: Ref<M[]>,
): () => void {
const onCreated = (item: M): void => {
const onCreated = (createdItem: M): void => {
// ignore items not matching the query or when no params are set
if (!params.value || !sift(params.value.query)(item)) {
if (!params.value || !sift(params.value.query)(createdItem)) {
return;
}

data.value = [...data.value, item];
// ignore items that already exist
if (data.value.find((item) => getId(createdItem) === getId(item)) !== undefined) {
return;
}

data.value = [...data.value, createdItem];
};

const onRemoved = (item: M): void => {
Expand Down
29 changes: 29 additions & 0 deletions test/useFind.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -427,6 +427,35 @@ describe('Find composition', () => {
expect(findComposition && findComposition.data.value).not.toContainEqual(additionalTestModel);
});

it('should ignore "create" events when item already exists', async () => {
expect.assertions(2);

// given
const emitter = eventHelper();
const feathersMock = {
service: () => ({
find: jest.fn(() => [additionalTestModel]),
on: emitter.on,
off: jest.fn(),
}),
on: jest.fn(),
off: jest.fn(),
} as unknown as Application;
const useFind = useFindOriginal(feathersMock);
let findComposition = null as UseFind<TestModel> | null;
mountComposition(() => {
findComposition = useFind('testModels');
});
await nextTick();

// when
emitter.emit('created', additionalTestModel);

// then
expect(findComposition).toBeTruthy();
expect(findComposition && findComposition.data.value).toHaveLength(1);
});

it('should listen to "patch" events', async () => {
expect.assertions(2);

Expand Down