rails / request.js

MIT License
389 stars 28 forks source link

Having trouble with TurboStream frame replacement #37

Closed DaveSanders closed 2 years ago

DaveSanders commented 2 years ago

Sorry if I'm missing something obvious, but I'm trying to do the following:

  1. post a form's contents to a rails controller
  2. controller does its work and returns turbo-streams
  3. have the page update the frames automatically

Right now, I can submit the data fine, see the controller working fine and it sends the two turbo-streams back to the browser, but request.js is not updating the frames. I do have window.Turbo defined.

Here's my stimulus controller where the call is made:

import { Controller } from "@hotwired/stimulus"
import { Turbo } from '@hotwired/turbo-rails'
import { post } from '@rails/request.js'

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

  async submit() {
    // Collect up the form field values
    let dd = this.formTarget.querySelectorAll('input,select')
    let data = {}
    dd.forEach((d) => {
      data[d.getAttribute('name')] = d.value
    })

    const url = this.formTarget.getAttribute('action')
    const response = await post(url, { responseKind: "turbo-stream", body: JSON.stringify(data) })
    if (response.ok) console.log("ok")
  }
}

And here's the relevant controller action:

    def save_mapping
      map_params = params.select { |p| p.start_with?('mapping') }

      import_map = []
      map_params.each do |map|
        import_map << [map[0].split('_')[1].to_i, map[1]]
      end

      @import.update(import_map: import_map)

      # TODO: Validate map

      mapping_data
      render turbo_stream: [
        turbo_stream.replace('example', partial: 'example'),
        turbo_stream.replace('mapping_form', partial: 'mapping_form')
      ]
    end

I've tried adding the responseKind and not adding it. I've also tried returning just one frame in my stream. It looks like everything is getting to the server and back, so I'm wondering if I'm not doing something I need to do on the return.

And I just tested it with the latest turbo-rails (0.8.1) but I had tested it previous with 0.7.10. On the stimulus side, I'm using stimulus-rails 0.6.0, but also tested with 0.4.2. Finally, I am using the latest request.js from August 10th, per skypack here.

Am I doing this wrong, or am I expecting it to do something it doesn't do? Thanks!

DaveSanders commented 2 years ago

Apologies - this was totally my error. Had a typo in the turbo-frame id on the html. Some days it just pays to stay in bed. Sheesh.