Skip to content
This repository has been archived by the owner on Jun 11, 2021. It is now read-only.

Commit

Permalink
fix(docsearch): hoist transformItems default value
Browse files Browse the repository at this point in the history
This fixes a bug where the `transformItems` function reference changes and the `autocomplete` instance is recreated every time.
  • Loading branch information
francoischalifour committed Jun 24, 2020
1 parent 13c4d15 commit 1e0ae9e
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 15 deletions.
6 changes: 5 additions & 1 deletion packages/docsearch-react/src/DocSearchModal.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -27,14 +27,18 @@ interface DocSearchModalProps extends DocSearchProps {
onClose?(): void;
}

function defaultTransformItems(x: DocSearchHit[]) {
return x;
}

export function DocSearchModal({
appId = 'BH4D9OD16A',
apiKey,
indexName,
placeholder = 'Search docs',
searchParameters,
onClose = noop,
transformItems = (x) => x,
transformItems = defaultTransformItems,
hitComponent = Hit,
resultsFooterComponent = () => null,
navigator,
Expand Down
30 changes: 16 additions & 14 deletions packages/website/src/theme/SearchBar/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,21 @@ function ResultsFooter({ state }) {
);
}

function transformItems(items) {
return items.map((item) => {
// We transform the absolute URL into a relative URL.
// Alternatively, we can use `new URL(item.url)` but it's not
// supported in IE.
const a = document.createElement('a');
a.href = item.url;

return {
...item,
url: `${a.pathname}${a.hash}`,
};
});
}

function DocSearch({ indexName, appId, apiKey, searchParameters }) {
const history = useHistory();
const [isOpen, setIsOpen] = useState(false);
Expand Down Expand Up @@ -85,20 +100,7 @@ function DocSearch({ indexName, appId, apiKey, searchParameters }) {
history.push(suggestionUrl);
},
}}
transformItems={(items) => {
return items.map((item) => {
// We transform the absolute URL into a relative URL.
// Alternatively, we can use `new URL(item.url)` but it's not
// supported in IE.
const a = document.createElement('a');
a.href = item.url;

return {
...item,
url: `${a.pathname}${a.hash}`,
};
});
}}
transformItems={transformItems}
hitComponent={Hit}
resultsFooterComponent={ResultsFooter}
/>,
Expand Down

1 comment on commit 1e0ae9e

@s-pace
Copy link
Collaborator

@s-pace s-pace commented on 1e0ae9e Jun 24, 2020

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Great fix 👏

Please sign in to comment.