Search code examples
stimulusjs

Instant search external resource with params


What does the code for loading query results from text search look like? There’s an example in handbook that loads external resource, is it as simple as that but appending query string to resource and capturing form data? I’m looking to make instant search where results are updated with every input event. For some reason google search for instant search yield examples that also use web socket part of hot wired, is that necessary and does it improve rendering performance? I’m hoping that turbo doesn’t simply tear up dom when replacing external resource.


Solution

  • I've written a Stimulus controller before that does something similar.

    You would attach a controller to your input element (or form), and the controller would have an event handler for the change event. Something like this:

    // your.html
    // <input type='text' data-controller="your_controller"/>
    
    // your_controller.js
    import { Controller } from "stimulus"
    export default class extends Controller {
    
      connect() {
        this.element.addEventListener('change', (e) => {
          // execute a fetch request or something here
        })
      }
    }