Created
February 22, 2022 23:09
-
-
Save jmarsh24/2eec2bf86962d3b12fef81c5e5fa5a12 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | |
}) | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<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