How to update multiple elements?


#1

I have a SJR endpoint which renders HTML for two different elements and then updates them. What is the proposed approach to do this with Stimulus?

With Stimulus, I can send only one HTML response from the server. So the only solution which I see is to parse the response and then update each element separately. But, I kind of don’t like this solution because SJR approach looks much simpler to me. Is there a better way how to do this with stimulus?

Thank you in advance for any ideas!


#2

Not sure if this is ideal…
but would a JSON response that contained 2 properties, where each property contained the rendered partial work?

def update
  # save changes here
  element1 = render_to_string 'partial1'
  element2 = render_to_string 'parial2'

  render json: { element1: element1, element2: element2 }
end
export default class extends Controller {
  static targets = ['element1', 'element2'];
  onUpdate(e) {
    const [data, status, xhr] = e.detail;
  
    this.element1Target.innerHTML = data.element1; // assuming properly escaped
    this.element2Target.innerHTML = data.element2;
  }
}