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:
- 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.
- 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.
Hi there,
in our application we are currently introducing a
ToggleSwitchFormand 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
view_components/app/components/primer/alpha/toggle_switch.ts
Lines 161 to 172 in ae8dbe2
In my opinion we have 2 options to tackle this:
fetchrequest to includeheaders: { Accept: "text/vnd.turbo-stream.html" }and when we have the response we triggerTurbo.renderStreamMessage(response.text()). But I am not sure if you want to tie your implementation to Turbo this closely.value, fill those and then trigger aform.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.