fetch(href, {
headers: {
Accept: "text/vnd.turbo-stream.html",
},
})
.then(r => r.text())
.then(html => Turbo.renderStreamMessage(html))
// optionally reflect the url .then(_ => history.replaceState(history.state, "", href))
import { Controller } from '@hotwired/stimulus'
export default class extends Controller {
static values = {
src: String,
}
connect() {
fetch(this.srcValue, {
headers: {
Accept: "text/vnd.turbo-stream.html",
},
}).then(r => r.text())
.then(html => Turbo.renderStreamMessage(html))
}
}
Turbo.fetch
Sure, here are a few examples of how to use Turbo's fetch method:
**Simple GET request:
This code makes a GET request to /data.json, waits for the response, and then logs the parsed JSON data to the console.
POST request with JSON payload:
This code creates a JSON payload object, sets the necessary headers and options for a POST request, and then uses Turbo.fetch to make the request to /api/users. The response is then parsed as JSON and logged to the console.
Using response data to navigate to a new page:
This code makes a GET request to /data.json, waits for the response, and then parses the JSON data. It then uses the data to construct a new URL and navigates to it using Turbo.visit.
Note that in all of these examples, await is used to wait for the response before continuing with the code. This is necessary because Turbo.fetch returns a Promise, which needs to be resolved asynchronously.