Created
April 14, 2021 19:03
-
-
Save andrewkatz/e9eddca62462f19d9a7d8ff82fa98194 to your computer and use it in GitHub Desktop.
Fetch Turbo stream
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
export default function () { | |
const token = document.querySelector('meta[name="csrf-token"]') | |
return token ? token.getAttribute('content') : null | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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