This pattern can help lazy load form fields in Rails using StimulusReflex which can be useful when calling an external API or loading slow relationships.
For example, let’s say you have a form where you want to pull in a list of GitHub repos for a user so they can display them on their profile.
Loading this data from GitHub’s API can take a couple of seconds depending on the number of repos the user has, so rather than delaying the entire form from loading we can instead load them asynchronously.
The initial /app/views/users/_form.html.erb would look something like this.
<%= form_with(model: user, url: [user], local: true) do |form| -%>
<div class="card">
<ul class="list-group list-group-flush">
<li class="list-group-item">
<%= form.text_field :name, label: "Name", placeholder: "Enter name", required: true %>
</li>
<li class="list-group-item">
<%= form.email_field :email, label: "Email", placeholder: "Enter email", required: true %>
</li>
</ul>
<div class="card-footer">
<%= form.submit "Save", class: "btn btn-secondary float-right" %>
</div>
</div>
<% end %>
Now add in another section for the repositories to the form, pretty simple just a label and div with a loading message which attaches our Stimulus controller.