1
0
Fork 0

refactor(docsearch): create search client hook

This commit is contained in:
François Chalifour 2020-04-10 14:47:51 +02:00
parent ec7df43e80
commit 950208f46c
4 changed files with 19 additions and 21 deletions

View file

@ -12,8 +12,9 @@ import {
InternalDocSearchHit,
StoredDocSearchHit,
} from './types';
import { createSearchClient, groupBy, noop } from './utils';
import { groupBy, noop } from './utils';
import { createStoredSearches } from './stored-searches';
import { useSearchClient } from './useSearchClient';
import { useTrapFocus } from './useTrapFocus';
import { Hit } from './Hit';
import { SearchBox } from './SearchBox';
@ -66,11 +67,7 @@ export function DocSearch({
).current;
useTrapFocus({ container: containerRef.current });
const searchClient = React.useMemo(() => createSearchClient(appId, apiKey), [
appId,
apiKey,
]);
const searchClient = useSearchClient(appId, apiKey);
const favoriteSearches = React.useRef(
createStoredSearches<StoredDocSearchHit>({
key: '__DOCSEARCH_FAVORITE_SEARCHES__',
@ -88,7 +85,7 @@ export function DocSearch({
const saveRecentSearch = React.useCallback(
function saveRecentSearch(item: InternalDocSearchHit) {
// We don't store `content` record, but their parent if available.
// We don't store `content` records, but their parent if available.
const search = item.type === 'content' ? item.__docsearch_parent : item;
// We save the recent search only if it's not favorited.

15
src/useSearchClient.ts Normal file
View file

@ -0,0 +1,15 @@
import React from 'react';
import algoliasearch from 'algoliasearch/dist/algoliasearch-lite.esm.browser';
import { version } from './version';
export function useSearchClient(appId: string, apiKey: string) {
const searchClient = React.useMemo(() => {
const client = algoliasearch(appId, apiKey);
client.addAlgoliaAgent(`docsearch (${version})`);
return client;
}, [appId, apiKey]);
return searchClient;
}

View file

@ -1,13 +0,0 @@
import algoliasearch from 'algoliasearch/dist/algoliasearch-lite.esm.browser';
import { version } from '../version';
export function createSearchClient(appId: string, apiKey: string) {
const searchClient = algoliasearch(appId, apiKey);
if (typeof searchClient.addAlgoliaAgent === 'function') {
searchClient.addAlgoliaAgent(`docsearch-react (${version})`);
}
return searchClient;
}

View file

@ -1,3 +1,2 @@
export * from './createSearchClient';
export * from './groupBy';
export * from './noop';