#community-help

Implementing Search Suggestion/Autocomplete Functionality in Typesense

TLDR Denis needed advice on implementing search suggestions in Typesense. Jason provided a solution for fetching after 3+ letters. However, questions on design pattern and passing hooks remain unanswered.

Powered by Struct AI

1

Apr 04, 2022 (21 months ago)
Denis
Photo of md5-4a36c3bc25964c64330a5747ba443346
Denis
11:30 AM
Hi!
We are trying to implement search suggestion/autocomplete functionality.

We want to fetch after 3+ letters only.
Is it possible, if it is, how to do it?

Dependencies: “react-instantsearch-dom”: “^6.21.1", “typesense-instantsearch-adapter”: “^2.2.0"

Typesense schema:

type Word = {
w: string;
lang: string;
};

import React, { useState } from "react";
import { SearchInput } from "../../components";
import TypesenseInstantsearchAdapter from "typesense-instantsearch-adapter";
import { InstantSearch } from "react-instantsearch-dom";

const Page = () => {
  const typesenseInstantSearchAdapter = new TypesenseInstantsearchAdapter({
    server: {
      apiKey: `${process.env.API_KEY}`,
      nodes: [
        {
          host: `${process.env.HOST}`,
          port: `${process.env.PORT}`,
          protocol: `https`,
        },
      ],
    },
    additionalSearchParameters: {
      queryBy: "word",
      perPage: 8, // we've tried perPage: search.length < 3 ? 0 : 8, but that causes re-renders and doesn't solve the problem since it still fetches.
    },
  });

  const [search, setSearch] = useState("");

  return (
    <div className="flex justify-center">
      <InstantSearch
        indexName="words"
        searchClient={typesenseInstantSearchAdapter.searchClient}
      >
        <SearchInput
          setSearch={setSearch}
          search={search}
          button={true}
          reload={false}
        />
      </InstantSearch>
    </div>
  );
};

export default Page;

Thanks in advance for any tips!
Jason
Photo of md5-8813087cccc512313602b6d9f9ece19f
Jason
03:56 PM
Denis Here's how to do this: https://www.algolia.com/doc/guides/building-search-ui/troubleshooting/faq/react/#how-to-search-from-the-n-th-character

You would have to replace "algoliaClient" with the searchClient that comes with the Typesense adapter
Denis
Photo of md5-4a36c3bc25964c64330a5747ba443346
Denis
05:37 PM
Thanks Jason! Managed to get it working. Another questions:

Is there another way to create the current searchbox + hits component without nesting the components? That would give us full control over the state?

Is it possible to pass down react hooks as props to components which use connectSearchBox or connectHits?

Thanks!
Jason
Photo of md5-8813087cccc512313602b6d9f9ece19f
Jason
06:07 PM
I'm not too sure about this answer to this Denis I haven't used react-instantsearch extensively myself. I'd recommend looking at Algolia's forums / github repos to see if this is possible

1