Skip to content

ToggleSwitchForm does not work with Turbo Responses #2940

Description

@klaustopher

Hi there,

in our application we are currently introducing a ToggleSwitchForm and we want the response to change a bit of state in the page. We are using turbo streams. The response we get is a proper turbo-stream response but since the request does not originate from a proper form request but instead a fetch request, turbo does not trigger.

See

try {
response = await fetch(this.src, {
credentials: 'same-origin',
method: 'POST',
headers: {
'Requested-With': 'XMLHttpRequest',
},
body,
})
} catch (error) {
throw new Error('A network error occurred, please try again.')
}

In my opinion we have 2 options to tackle this:

  1. We allow to pass a parameter into the ToggleSwitchForm that adds a data attribute to tell the component that it is rendered in a turbo context and then change the fetch request to include headers: { Accept: "text/vnd.turbo-stream.html" } and when we have the response we trigger Turbo.renderStreamMessage(response.text()). But I am not sure if you want to tie your implementation to Turbo this closely.
  2. Another option would be that instead of building a fetch request, we add hidden form inputs for the CSRF token and the value, fill those and then trigger a form.submit() to have the request be executed as a normal form submission.

I'll be happy to submit a PR for either solution if you let me know which one is the preferred way.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions