Blog>
Snippets

Configuring React Query with Algolia for Data Fetching

Showcase the configuration steps necessary to use React Query for fetching and handling data from Algolia, including query keys and asynchronous query functions.
import { useQuery } from 'react-query';
import algoliasearch from 'algoliasearch/lite';
First, import the useQuery hook from react-query and algoliasearch from the algoliasearch/lite package.
const algoliaClient = algoliasearch('YourApplicationID', 'YourSearchOnlyApiKey');
Initialize the Algolia client with your Application ID and Search-Only API Key.
const fetchAlgoliaData = async (key, query) => {
    const index = algoliaClient.initIndex(key);
    const { hits } = await index.search(query);
    return hits;
};
Define an asynchronous function to fetch data from Algolia. It takes a key representing the index name and a query string.
const useAlgoliaQuery = (indexName, query) => {
    return useQuery(['algolia', indexName, query], () => fetchAlgoliaData(indexName, query));
};
Create a custom hook, useAlgoliaQuery, using the useQuery hook from React Query. It takes the index name and query string as parameters, uses them to construct a query key array, and calls fetchAlgoliaData.