Implementing an Autocomplete Search Box Using React Query and Algolia
Provide a code example for creating a dynamic autocomplete search component using React Query for data management and Algolia for search capabilities.
import { useQuery } from 'react-query';
import algoliasearch from 'algoliasearch/lite';
import { useState } from 'react';
Import necessary libraries and hooks. React Query for fetching data, Algoliasearch for searching, and useState for managing the search query state.
const searchClient = algoliasearch('YourApplicationID', 'YourSearchOnlyAPIKey');
const index = searchClient.initIndex('YourIndexName');
Initialize Algolia search client with your application ID and search-only API key, and specify the index you want to search within.
function useAlgoliaQuery(query) {
return useQuery(['algoliaSearch', query], () => index.search(query), {
enabled: !!query,
keepPreviousData: true
});
}
Define a custom hook using React Query to fetch search results from Algolia. The search is only triggered if the query is not empty.
function AutocompleteSearchBox() {
const [query, setQuery] = useState('');
const { data, isFetching } = useAlgoliaQuery(query);
return (
<div>
<input
type='text'
placeholder='Search...'
value={query}
onChange={(e) => setQuery(e.target.value)}
/>
{isFetching && <div>Loading...</div>}
<ul>
{data?.hits.map((hit) => (
<li key={hit.objectID}>{hit.name}</li>
))}
</ul>
</div>
);
}
Create the AutocompleteSearchBox component that utilizes the useAlgoliaQuery hook to fetch and display search results. Includes an input for the query and displays results in a list.