Skip to content

Instantly share code, notes, and snippets.

@jmarsh24
Created February 22, 2022 23:09
Show Gist options
  • Save jmarsh24/2eec2bf86962d3b12fef81c5e5fa5a12 to your computer and use it in GitHub Desktop.
Save jmarsh24/2eec2bf86962d3b12fef81c5e5fa5a12 to your computer and use it in GitHub Desktop.
import { Controller } from '@hotwired/stimulus'
import axios from 'axios'
import { autocomplete } from '@algolia/autocomplete-js'
export default class extends Controller {
static targets = ['field']
search (query, callback) {
axios.get('/search_suggestions', { params: { query } }).then(response => {
callback(response.data)
})
}
connect () {
this.ac = autocomplete(this.fieldTarget, { hint: false }, [
{
source: this.search,
debounce: 200,
templates: {
suggestion: function (suggestion) {
return suggestion
}
}
}
]).on('autocomplete:selected', (event, suggestion, dataset, context) => {
this.ac.autocomplete.setVal(suggestion)
})
}
}
<div class="autocompleteContainer" data-controller="autocomplete">
<%= form_with(url: root_path, method: :get, local: true, class: "searchBarContainer") do |form| %>
<%= form.text_field :query,
value: @current_search,
placeholder: "Search #{number_with_delimiter(@videos_total)} videos...",
class: 'searchBar',
'data-autocomplete-target': "field",
'data-autocomplete-url': "/search_suggestions" %>
<div id="autocomplete"></div>
<%= form.button fa_icon("search"), class: "searchButton", name: nil %>
<% end %>
</div>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment