Skip to content

Instantly share code, notes, and snippets.

@andrewkatz
Created April 14, 2021 19:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save andrewkatz/e9eddca62462f19d9a7d8ff82fa98194 to your computer and use it in GitHub Desktop.
Save andrewkatz/e9eddca62462f19d9a7d8ff82fa98194 to your computer and use it in GitHub Desktop.
Fetch Turbo stream
export default function () {
const token = document.querySelector('meta[name="csrf-token"]')
return token ? token.getAttribute('content') : null
}
import getCSRFToken from './csrf'
export function fetchTurbo ({ url, body = {} }) {
const token = getCSRFToken()
fetch(url, {
method: 'POST',
body: new URLSearchParams({ authenticity_token: token, ...body }),
headers: {
'X-CSRF-Token': token,
Accept: 'text/vnd.turbo-stream.html, text/html, application/xhtml+xml'
}
}).then((response) => response.text())
.then((response) => {
document.body.insertAdjacentHTML('afterend', response)
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment