Live search without the entire page reload, just the partial

Hey @SylarRuby!

You would just return a fully rendered HTML response with no layout and inject it into the page in a situation like this, rather than completely render a new page for Turbolinks to process. See this recent post for some more talk about remotely fetching some data and dropping it into the page. The gist of it is that in many scenarios it’s possible to have a single controller that can be reused across various use cases involving remotely fetching data. That controller could be as simple as:

remote_partial_controller.js

import { Controller } from 'stimulus'

export default class extends Controller {
  static targets = ['display']

  render(evt) {
    this.displayTarget.innerHTML = evt.detail[0].body.innerHTML
  }
}

For your situation, you would just have your input submit a remote form (the form will be remote by default in Rails) and configure an action that tells RemotePartialController to render the response.

Now, you may have additional logic necessary for the autocomplete search (for instance don’t perform a search until there are at least two characters). In your example, you’re using a FooController with a #search method for this. That controller and the RenderPartialController can happily live side by side here, but if it’s easier or makes more sense, you can easily just take the RenderPartialController#render method and move that into your FooController.

Also, in your FooController, you’ll want to submit the form via Rails.fire(form, 'submit') rather than call Turbolinks.visit. Then have an action that triggers render when a response is returned from the form submission.

I hope that makes sense, I’m happy to go into more depth if necessary. I unfortunately don’t have time to write up a full working example, but if that would be helpful I can whip one up later.

Regarding the quote:

it’s replacing the DOM inline (really just the body) - it’s not actually clearing the current page from memory and loading a new one, as would typically happen when you navigate from page to page in a non-SPA situation. This means it doesn’t have to re-parse any JS or CSS payloads. SPAs have this advantage, too, but SPAs are also tied to an API and you’re rendering a JSON payload on the backend and then rendering HTML on the frontend. With Turbolinks, you skip the JSON, render the HTML on the backend, and assuming you keep your backend fast you’ll realize some of the advantages of a SPA but typically with a lot less code and complexity by just writing code like a non-SPA website.

Hope this helps!

1 Like