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(autocomplete-js): display warning when there are more than one instances of autocomplete #1108

Merged
merged 4 commits into from
Mar 16, 2023
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
18 changes: 18 additions & 0 deletions packages/autocomplete-js/src/__tests__/autocomplete.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,24 @@ beforeEach(() => {
});

describe('autocomplete-js', () => {
test('warns when more than one instance is detected in a document', () => {
const firstContainer = document.createElement('div');
expect(() =>
autocomplete({
container: firstContainer,
})
).not.toWarnDev();

const secondContainer = document.createElement('div');
expect(() =>
autocomplete({
container: secondContainer,
})
).toWarnDev(
'[Autocomplete] Multiple instances of Autocomplete are not currently supported and can introduce unwanted behavior during user interaction. Please destroy the previous instance before creating a new one.'
);
});

test('renders with default options', () => {
const container = document.createElement('div');
autocomplete<{ label: string }>({
Expand Down
11 changes: 11 additions & 0 deletions packages/autocomplete-js/src/autocomplete.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import {
createRef,
debounce,
getItemsCount,
warn,
} from '@algolia/autocomplete-shared';
import htm from 'htm';

Expand All @@ -27,6 +28,8 @@ import {
import { userAgents } from './userAgents';
import { mergeDeep, pickBy, setProperties } from './utils';

let instancesCount = 0;

export function autocomplete<TItem extends BaseItem>(
options: AutocompleteOptions<TItem>
): AutocompleteApi<TItem> {
Expand Down Expand Up @@ -336,6 +339,7 @@ export function autocomplete<TItem extends BaseItem>(
});

function destroy() {
instancesCount--;
cleanupEffects();
}

Expand Down Expand Up @@ -397,6 +401,13 @@ export function autocomplete<TItem extends BaseItem>(
});
}

warn(
instancesCount === 0,
'Multiple instances of Autocomplete are not currently supported and can introduce unwanted behavior during user interaction. Please destroy the previous instance before creating a new one.'
dhayab marked this conversation as resolved.
Show resolved Hide resolved
);

instancesCount++;

return {
...autocompleteScopeApi,
update,
Expand Down