Skip to content
Branch: master
Find file Copy path
Find file Copy path
Fetching contributors…
Cannot retrieve contributors at this time
119 lines (86 sloc) 2.77 KB
title lastmod publishdate author draft description tags youtube github type
Algolia Search with Svelte
2019-08-25 13:07:30 -0700
2019-08-25 13:07:30 -0700
Jeff Delaney
Algolia InstantSearch with Svelte 3

{{% box emoji="👀" %}} This tutorial is an extension of the Algolia Cloud Functions Guide. You must have the Cloud Functions deployed to start making instant search queries from your frontend app. {{% /box %}}

Install Algolia

Algolia does not provide official support for Svelte, but we can easily implement our own custom UI with AlgoliaSearch.

Note. You can also use InstantSearch.js if you want pre-built components.

{{< file "terminal" "command line" >}} {{< highlight terminal >}} npm install algoliasearch {{< /highlight >}}

Update the index.html

The Algolia client makes a reference to process, which does not exist in the browser. Add the code below to prevent errors.

{{< file "html" "public/index.html" >}} {{< highlight html >}} <title>Svelte app</title>

<!-- ADD THIS LINE -->
<script>window.process = {env: { DEBUG: undefined } }</script>

{{< /highlight >}}

Svelte Algolia Search Component

The component below initializes the AlgoliaSearch lite, then binds a request to each keyup event on a form input. Algolia returns an object with the resulting hits, which are updated on the component's hit property.

{{< file "svelte" "Search.svelte" >}} {{< highlight html >}}

<script> import { onMount } from 'svelte'; import algoliasearch from 'algoliasearch/lite'; let searchClient; let index; let query = ''; let hits = []; onMount(() => { searchClient = algoliasearch( 'YOUR-APP-ID', 'YOUR-SEARCH-ONLY-KEY' ); index = searchClient.initIndex('customers'); // Warm up search{ query }).then(console.log) }); // Fires on each keyup in form async function search() { const result = await{ query }); hits = result.hits; console.log(hits) } </script> <style> :global(em) { color: red; font-weight: bold; background: black; } </style>

Svelte InstantSearch

{#each hits as hit} {hit.username}

{hit.username} {hit.objectID}

	<p contenteditable bind:innerHTML={}></p>

{/each} {{< /highlight >}}

{{< figure src="/img/snippets/svelte-algolia.png" caption="Demo of Algolia Search in Svelte 3" >}}

You can’t perform that action at this time.