Clients

React hooks

Give a React tree one Narsil client or one engine in the page, search as somebody types, offer completions under the box, and read documents, stats, and tasks through hooks that share their requests.

@delali/narsil/react wraps the TypeScript client in hooks that re-render their component when the server answers, so a component can show a search result, a document, or a task without handling the request itself. A provider can also hold an engine that works in the page, in which case the same hooks search that engine with no server in between. The provider shares requests between the hooks under it, so when two components pass the same arguments to the same hook, the provider sends one request and both components receive that answer.

On this page, you'll build a help-centre search box in narsil-client.ts, App.tsx, and HelpSearch.tsx, add completions under it, and then move the search into the page. Each code block below holds a whole file, with green lines marking the lines that you add at each step and struck lines marking the lines that you remove.

Give the tree one client

Every hook below a NarsilProvider sends its requests through the provider's client. React 19.2 or later is an optional peer dependency of the package, while no other entry point imports React. Build the client once, in a separate module, because a component that builds the client during render builds a new one each time, which makes every hook under the provider start again. Point the client at a path on the page's origin, and have your server forward the requests under that path to Narsil with the key attached, so that the key stays off the page. There is more on that setup on the TypeScript client page.

narsil-client.ts
import { createNarsilClient } from '@delali/narsil/client'
 
export const narsilClient = createNarsilClient({ url: '/search-api', maxResponseBytes: 1_048_576 })
App.tsx
import type { ReactElement } from 'react'
import { NarsilProvider } from '@delali/narsil/react'
import { HelpSearch } from './HelpSearch'
import { narsilClient } from './narsil-client'
 
export const App = (): ReactElement => (
  <NarsilProvider client={narsilClient}>
    <HelpSearch />
  </NarsilProvider>
)

A hook outside any provider throws a NarsilError with CONFIG_INVALID, because it has no client to send through. With maxResponseBytes set to 1,048,576, the client stops reading an answer past one MiB, so that an answer that grows without limit can't exhaust the memory of the tab.

Search as somebody types

useQuery takes the index name and the same parameters as query, and it sends the request again whenever they change. With enabled set to false while the box is empty, the hook sends nothing. With keepPreviousData, the hook keeps the last hits on screen while it waits for the next answer, so the list stays in place between keystrokes.

HelpSearch.tsx
import { type ChangeEvent, type ReactElement, useCallback, useState } from 'react'
import { useQuery } from '@delali/narsil/react'
 
interface Article {
  title: string
}
 
export const HelpSearch = (): ReactElement => {
  const [term, setTerm] = useState('')
  const handleTermChange = useCallback((event: ChangeEvent<HTMLInputElement>): void => {
    setTerm(event.target.value)
  }, [])
  const search = useQuery<Article>(
    'articles',
    { term, limit: 5, document: { include: ['title'] } },
    { enabled: term.trim().length > 0, keepPreviousData: true }
  )
 
  return (
    <section>
      <input type="search" value={term} onChange={handleTermChange} aria-label="Search the help centre" />
      {search.isLoading && <p>Searching</p>}
      {search.error && <p role="alert">{search.error.message}</p>}
      <ul>
        {search.data?.hits.map((hit) => (
          <li key={hit.id}>{hit.document?.title}</li>
        ))}
      </ul>
    </section>
  )
}

With the three articles from the TypeScript client page in the index, the list shows 'How a refund reaches your bank' and 'Refunds in another currency' once somebody types refund. isLoading is true while the hook waits for an answer and has none to show, which under keepPreviousData happens only before the first answer. isFetching, however, is true during every request, a refresh included, so use it for a quieter indicator. error holds the NarsilError of the last failed request until the hook receives a successful answer. The hook takes no abort signal, because the provider stops waiting for a request once two seconds pass with no mounted component that uses its answer.

Offer completions under the box

useSuggest returns completions of a prefix from the terms that the index holds, with the most widely used term first. The component below requests completions for the last word once that word has two letters. When somebody clicks a completion, the component puts it in place of that word. A search for ref matches no article, because a plain search matches whole words. However, the completions under the box include refund, so somebody can click it to search for refund, which matches both refund articles.

HelpSearch.tsx
import { type ChangeEvent, type ReactElement, useCallback, useState } from 'react'
import { useQuery } from '@delali/narsil/react'
import { useQuery, useSuggest } from '@delali/narsil/react'
 
interface Article {
  title: string
}
 
interface CompletionProps { 
  term: string
  onPick: (term: string) => void
}
 
const Completion = ({ term, onPick }: CompletionProps): ReactElement => {
  const handleClick = useCallback((): void => {
    onPick(term)
  }, [onPick, term])
 
  return (
    <li>
      <button type="button" onClick={handleClick}>
        {term}
      </button>
    </li>
  )
}
 
export const HelpSearch = (): ReactElement => {
  const [term, setTerm] = useState('')
  const handleTermChange = useCallback((event: ChangeEvent<HTMLInputElement>): void => {
    setTerm(event.target.value)
  }, [])
  const handlePick = useCallback((completion: string): void => { 
    setTerm((current) => current.replace(/\S*$/, completion))
  }, [])
  const search = useQuery<Article>(
    'articles',
    { term, limit: 5, document: { include: ['title'] } },
    { enabled: term.trim().length > 0, keepPreviousData: true }
  )
  const lastWord = term.split(/\s+/).at(-1) ?? ''
  const completions = useSuggest('articles', { prefix: lastWord, limit: 3 }, { enabled: lastWord.length >= 2 })
 
  return (
    <section>
      <input type="search" value={term} onChange={handleTermChange} aria-label="Search the help centre" />
      <ul aria-label="Completions"> // [!code ++:5]
        {completions.data?.terms.map((entry) => (
          <Completion key={entry.term} term={entry.term} onPick={handlePick} />
        ))}
      </ul>
      {search.isLoading && <p>Searching</p>}
      {search.error && <p role="alert">{search.error.message}</p>}
      <ul>
        {search.data?.hits.map((hit) => (
          <li key={hit.id}>{hit.document?.title}</li>
        ))}
      </ul>
    </section>
  )
}

Each completion is a separate component, so that its click handler holds the term of that completion. The hook returns each completion in the spelling that the documents hold, because the engine records every spelling that the stemmer changes. There is more on the stemmer on the full-text search page. With refund dis in the box, the completions include dispatch while the two refund articles stay on screen.

Search an engine in the page

A page that holds its documents in the browser, such as a help centre that bundles its articles into the page or a list that somebody keeps offline, can give the provider an engine in place of a client. Every read hook then calls the engine method of the same name, so HelpSearch.tsx works unchanged. Create the engine outside the component tree, for the same reason as the client.

narsil-engine.ts
import { createNarsil } from '@delali/narsil'
 
export const narsilEngine = await createNarsil()
 
await narsilEngine.createIndex('articles', { schema: { title: 'string', body: 'string' } })
await narsilEngine.insertBatch('articles', [
  { id: 'refund-timing', title: 'How a refund reaches your bank', body: 'A refund returns to the card that paid for the order.' },
  { id: 'parcel-tracking', title: 'Track a parcel after dispatch', body: 'Every dispatched order has a tracking code.' },
  { id: 'refund-currency', title: 'Refunds in another currency', body: 'Your bank converts a refund at the rate on the day it arrives.' },
])
App.tsx
import type { ReactElement } from 'react'
import { NarsilProvider } from '@delali/narsil/react'
import { HelpSearch } from './HelpSearch'
import { narsilClient } from './narsil-client'
import { narsilEngine } from './narsil-engine'
 
export const App = (): ReactElement => (
  <NarsilProvider client={narsilClient}> // [!code --]
  <NarsilProvider engine={narsilEngine}> // [!code ++]
    <HelpSearch />
  </NarsilProvider>
)

The box shows the same two refund articles for refund and the same completions as before, while the engine computes every answer in the page. The provider listens for the engine's write event. When the page inserts a third refund article into narsilEngine, every hook on the articles index sends its search again once 200 ms pass with no further write to that index, so the list grows to three titles. Set refreshAfterWriteMs on the provider for a longer or a shorter wait. Because the hooks only read, a component that writes imports the engine and calls the write method on it.

Under an engine, useTask, useTasks, and useImport throw CONFIG_INVALID as they render, because only a server handles tasks and imports. useNarsilClient throws the same code, because the provider holds no client. The hooks pass neither headers nor timeoutMs to an engine. The provider throws CONFIG_INVALID when its props set both a client and an engine, or neither.

Read documents, stats, and tasks

The other hooks work in the same way, each returning the answer of the matching method:

HookWhat it returns
useDocument(indexName, docId)It returns one stored document, or undefined with no error for an id that the index lacks. When docId is missing, the hook sends no request.
useDocuments(indexName, params)It returns a page of documents in id order, as listDocuments does.
usePreflight(indexName, params)It returns the number of hits that the search matches, without the hits.
useIndexes() and useStats(indexName)useIndexes returns the engine's indexes, while useStats returns the counts and the memory estimate of one index.
useTask(taskId) and useTasks()useTask polls one task record every 250 ms until the task finishes, and useTasks returns the list of tasks. Both need a client.
useImport(indexName)It returns a start function that sends a corpus as a task, along with the progress, the result, and a cancel function. It needs a client.
useNarsilClient()It returns the provider's client, for a write or any other call that has no hook.

Every read hook takes enabled, keepPreviousData, refreshIntervalMs, headers, and timeoutMs as its last argument, while useTask takes pollIntervalMs in place of refreshIntervalMs. With refreshIntervalMs, a hook requests its answer again on that interval and pauses while the page is hidden. refresh() requests the answer once more when you call it. The provider keeps each answer for two seconds after the last component that uses it unmounts, so when somebody navigates straight back, the component shows the same result with no second request. Set keepAliveMs on the provider to change that interval. useImport stops its polling when the component unmounts, while the server finishes the load, so follow the load again with useTask and the id that start returns.

Where to go next

  • Read TypeScript client for the client that the hooks send through, its deadlines, and its failures.
  • Read React Native for an engine inside an iOS or Android app.
  • Read Errors for the codes in a hook's error and for why isNarsilError is the test to use.