{"size": 1470, "ext": "js", "max_stars_repo_path": "app/pixels.chrisesplin.com/components/hooks/use-algolia.js", "max_stars_repo_name": "javascpdev/pixels", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "app/pixels.chrisesplin.com/components/hooks/use-algolia.js", "max_issues_repo_name": "javascpdev/pixels", "max_issues_repo_issues_event_min_datetime": "2020-09-07T15:45:03.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-22T12:13:32.000Z", "max_forks_repo_path": "app/pixels.chrisesplin.com/components/hooks/use-algolia.js", "max_forks_repo_name": "deltaepsilon/pixels", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null}
{"max_stars_count": null, "max_issues_count": 9, "max_forks_count": null, "avg_line_length": 27.2222222222, "max_line_length": 90, "alphanum_fraction": 0.6510204082}
import { useEffect, useMemo, useState } from 'react';

import algoliasearch from 'algoliasearch';
import useCurrentUser from '~/hooks/use-current-user';
import useEnvironment from '~/hooks/use-environment';
import useFirebase from '~/hooks/use-firebase';

const DEFAULT_RESULTS = { hits: [] };

export default function useAlgolia({ query, indexKey }) {
  const environment = useEnvironment();
  const firebase = useFirebase();
  const currentUser = useCurrentUser();
  const [client, setClient] = useState(null);

  const index = useMemo(
    () => client?.initIndex && client.initIndex(environment.algolia.indices[indexKey]),
    [client, indexKey]
  );
  const [results, setResults] = useState(DEFAULT_RESULTS);

  useEffect(() => {
    (async () => {
      const currentUser = firebase.auth().currentUser;

      if (currentUser && environment && indexKey) {
        await currentUser.getIdToken(true);

        const { claims } = await currentUser.getIdTokenResult();

        const client = algoliasearch(environment.algolia.applicationId, claims.searchKey);

        setClient(client);
      }
    })();
  }, [currentUser, environment, indexKey, setClient]);

  useEffect(() => {
    if (index && query) {
      let isMounted = true;

      (async () => {
        const results = await index.search(query);

        isMounted && setResults(results);
      })();

      return () => (isMounted = false);
    }
  }, [index, query, setResults]);

  return results;
}
