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

react-meilisearch

v1.0.1

Published

react client for integration with meilisearch server

Downloads

4

Readme

React-Meilisearch

The React client api for integrating with Meilisearch Server. It includes several simple hooks to help you integrate with your search server. We based it on the meilisearch npm package.

GitHub package.json version (branch) GitHub issues GitHub GitHub repo file count npm bundle size

Install

npm install react-meilisearch

Getting Started

Initialization

First you need to initialize a meilisearch client and connect it to React.

import { MeiliSearchProvider, MeiliSearchClient } from 'react-meilisearch';
import './App.css'

const App = () => {
  const meilisearch = new MeiliSearchClient({
    host: 'http://localhost:7700',
    apiKey: 'masterKey',
  })

  return (
    <MeiliSearchProvider client={meilisearch}>
      // ... rest of App.jsx
    </MeiliSearchProvider>
  )
}

export default App

UseSearch Hook

This hook recieves a query, index and advanced search options, triggers the search and returns the current state of the search.

const { loading, error, data } = useSearch({ index: 'movies', query: 'Comedy' });

Full Example:

In the following example we used the hook along with a 'query' search parameter, using the use-search-params hook.

import { useSearch } from 'react-meilisearch';
import { useSearchParams } from 'react-router-dom';

const UseSearchExample = () => {
    const [searchParams] = useSearchParams();
    const { loading, error, data } = useSearch({ index: 'movies', query: searchParams.get('query') });

    if (loading) return 'Loading...';
    if (error) return 'Error!';
    
    return (
        <div>
            {
                data &&
                <div>results count {data.hits.length}</div>
            }
        </div>
    )
}

export default UseSearchExample;

Parameters

| parameter | type | description | default value | | ------ | ------ | ------ | ------ | | query | string | the query to search by | '' | | index | string | the melisearch index to search in | '' | | options | SearchParams | meilisearch search options described in the documentation | { limit: 30 } |

Return Value

| parameter | type | description | | ------ | ------ | ------ | | loading | boolean | is the search in progress | | error | MeiliSearchError / null | an error occured in the search request | | data | SearchResponse<Record<string, any>> / undefined / null | the search result | | refetch | (SearchArguments (same as the hook parameters)) => void | method to refetch the search | | fetchMore | (FetchMoreParameters (same as the hook parameters with the callback updateResult)) => void | method to fetch more results, read Infinite Scroll for more details |

UseLazySearch Hook

Works the same way as Use Search hook, but returns a search funtion instead of triggering it when the component is mounted.

const [search, { loading, error, data }] = useLazySearch({ index: 'movies' });
search('Comedy');

Full Example:

import { useLazySearch } from 'react-meilisearch';

const UseLazySearchExample = () => {
    const [search, { loading, error, data }] = useLazySearch({ index: 'movies' });

    if (loading) return 'Loading...';
    if (error) return 'Error!';

    return (
        <div>
            <input onChange={(event) => {
                search(event.target.value, { options: {
                    limit: 100
                } });
            }} />
            {
                data &&
                <div>results count {data.hits.length}</div>
            }
        </div>
    )
}

export default UseLazySearchExample;

Parameters

| parameter | type | description | default value | | ------ | ------ | ------ | ------ | | query | string | the query to search by | '' | | index | string | the melisearch index to search in | '' | | options | SearchParams | meilisearch search options described in the documentation | { limit: 30 } |

Return Value

| parameter | type | description | | ------ | ------ | ------ | | search function | (SearchArguments (same as the hook parameters)) => void | Trigger a search using the given parameters. The function parameters overide the hook parameters | | loading | boolean | is the search in progress | | error | MeiliSearchError / null | an error occured in the search request | | data | SearchResponse<Record<string, any>> / undefined / null | the search result | | fetchMore | (FetchMoreParameters (same as the hook parameters with the callback updateResult)) => void | method to fetch more results, read Infinite Scroll for more details |

UseMeilisearchClient Hook

Use this hook to get the meilisearch client and use it's normal methods described in the meilisearch npm package.

const meilisearchClient = useMeiliSearchClient();

Full Example:

import { useState } from 'react';
import { useMeiliSearchClient } from 'react-meilisearch';

const UseMeiliSearchClientExample = () => {
    const meilisearchClient = useMeiliSearchClient();
    const [searchResults, setSearchResults] = useState(null);

    const onChange = (event) => {
        meilisearchClient.index('movies').search(event.target.value)
        .then(setSearchResults);
    }
    
    return (
        <div>
            <input onChange={onChange} />
            {
                searchResults &&
                <div>results count {searchResults.hits.length}</div>
            }
        </div>
    )
}

export default UseMeiliSearchClientExample;

Infinite Scroll

You can easily implement infinite scroll or pagination search using the fetchMore function. In the example below we used react-infinite-scroll-hook npm package to handle the scroll events. Feel free to change it to whatever you want.

import { useSearch } from 'react-meilisearch';
import useInfiniteScroll  from 'react-infinite-scroll-hook';
import './infiniteScrollExample.css';

const InfiniteScrollExample = ({ query }) => {
    const { loading, error, data, fetchMore } = useSearch({ query, index: 'movies', options: {
        limit: 30,
        offset: 0,
    } });

    const hasNextPage = data && data.estimatedTotalHits > data.hits.length;
    const loadMore = () => fetchMore({ options: { offset: data.hits.length }});

    const [sentryRef, { rootRef }] = useInfiniteScroll({
        loading,
        hasNextPage,
        onLoadMore: loadMore,
        disabled: !!error,
        rootMargin: '0px 0px 200px 0px',
      });

    if (loading) return 'Loading...';
    if (error) return 'Error!';

    return (
        <div className='infinite-scroll' ref={rootRef}>
            {
                data && data.hits.map(hit => (
                    <div key={hit.key}>{hit.title}</div>
                ))
            }
            {
                (loading || hasNextPage) && (
                    <div ref={sentryRef}/>
                  )
            }
        </div>
    )
}

export default InfiniteScrollExample;

The default behavior of the fetchMore result is to concat the result hits with the previous data hits. You can override this behavior by giving the fetchMore an alternative updateResult callback. Make sure you are returning the new data value.

const updateResult = (prev, fetchMoreResult) => {
    console.log('I am overriding the default updateResult function');
    return (
    {
        ...prev,
        offset: fetchMoreResult.offset,
        hits: [...prev.hits, ...fetchMoreResult.hits]
    })
}
const loadMore = () => fetchMore({ options: {offset: data.hits.length}, updateResult });

Types

All of the meilisearch types are available for you, in addition to these new ones:

type SearchArguments = {
   query: string;
   index: string;
   options: SearchParams;
}

type FetchMoreParameters = SearchArguments & {
   updateResult: (prev: SearchResponse<Record<string, any>>,
                  fetchMoreResult: SearchResponse<Record<string, any>>) 
                   => SearchResponse<Record<string, any>>,
   onError?: (error: MeiliSearchError) => void;
}

type UseSearchResult = {
   loading: boolean;
   error: MeiliSearchError | null;
   data: SearchResponse<Record<string, any>> | undefined | null;
   refetch?: (searchParameters: SearchArguments) => void;
   fetchMore: (searchParameters: FetchMoreParameters) => void;
}

License

MIT