npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

use-algolia

v1.5.3

Published

Dead-simple React hook to make Algolia search queries. Supports pagination out of the box.

Downloads

2,573

Readme

useAlgolia npm latest release Minified size

Dead-simple React hook to make Algolia search queries. Supports pagination out of the box.

Code snippet

Installation

Requires React >= 16.8.0 and algoliasearch 4.

yarn add react algoliasearch use-algolia

Usage

Pass the Algolia app ID, search API key, and index name to the hook call.

If you don’t have one of the three on the first hook call, pass in an empty string first. See the example below.

Optionally, pass the initial request options as the fourth argument.
See https://www.algolia.com/doc/api-reference/search-api-parameters/ for all options.

Access the returned hits, response, loading, and hasMore from searchState.

const [searchState, requestDispatch, getMore] = useAlgolia(
  APP_ID,
  SEARCH_KEY,
  INDEX_NAME,
  { query: 'construction' }
);

const { hits, response, loading, hasMore } = searchState;

Making new requests

Call requestDispatch with options to make a new Algolia search request. Note this will shallow merge your previous request options. Making new requests will immediately reset hits to an empty array and set loading to true.

requestDispatch({ query: 'bin chicken' });

// Create a new request with query: 'bin chicken' AND the filters below.
requestDispatch({ filters: 'city:Sydney OR city:Melbourne' });

// Creates a new request, resetting query and filters. Same as retrieving all objects.
requestDispatch({ query: '', filters: '' });

Loading more hits with pagination

Call getMore to get the next page of hits. Get all hits from searchState.hits, not searchState.response.hits.

You could also manually pass in page to requestDispatch to get a specific page or skip pages. Calling getMore after doing so will still work.

Increasing number of hits per page

Include hitsPerPage in your request. Initially set to Algolia’s default of 20.

const [searchState, requestDispatch, getMore] = useAlgolia(
  APP_ID,
  SEARCH_KEY,
  INDEX_NAME,
  { hitsPerPage: 100 }
);

// OR after initial query:
requestDispatch({ hitsPerPage: 100 });

Specifying hit type

If you’re using TypeScript, pass the hit type as the generic type parameter. Hits will have objectID.

type Hit = {
  title: string;
  year: number;
  actors: string[];
};

const [searchState, requestDispatch, getMore] = useAlgolia<Hit>(
  APP_ID,
  SEARCH_KEY,
  INDEX_NAME
);

// hits will have type readonly (Hit & ObjectWithObjectID)[]
const { hits } = searchState;

Changing query index or other Algolia config

When the appId, searchKey, or indexName passed to the hook call updates, the index is reinitialised with the new config.

You can also use the setAlgoliaConfig function returned by the hook:

const [, , , setAlgoliaConfig] = useAlgolia('', '', '');

setAlgoliaConfig({
  appId: APP_ID,
  searchKey: SEARCH_KEY,
  indexName: INDEX_NAME,
});

Doing either will automatically do the first query on the new index if all three items are provided.

Searching for facet values

You can access the search index created by the hook in searchState to call the searchForFacetValues method. See https://www.algolia.com/doc/api-reference/api-methods/search-for-facet-values/

Note: index may be null if one of appId, searchKey, or indexName is missing or invalid in searchState. See Changing query index or other Algolia config above.

const [searchState] = useAlgolia('', '', '');
const { index } = searchState;

if (index) index.searchForFacetValues('city');

State

| Key | Type | Description | | ------------- | ------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | hits | (Hit & ObjectWithObjectID)[] | Contains all hits for search query, including all pages retrieved. | | response | SearchResponse or null | Response to last query. Contains only last page of hits retrieved. Initially null. See https://www.algolia.com/doc/api-reference/api-methods/search/#response | | loading | boolean | True if a request is being loaded, either to load initial request or when loading more hits. | | hasMore | boolean | True if there are more pages to be retrieved. | | appId | string | Algolia App ID. | | searchKey | string | API key to search the index. | | indexName | string | Algolia index to query. | | index | SearchIndex or null | Exposed Algolia search index. Note we use the lite client, which only supports the search and searchForFacetValues methods. | | request | SearchOptions | Exposed search request options passed to the last request. From previous requestDispatch calls. |


Credits

Based on the original hook by @shamsmosowi.

Bootstrapped with tsdx and published with np.