Skip to content

Commit 775f1eb

Browse files
authored
Merge pull request #21 from excid3/cache-response-body
This saves the `text` and `json` values after reading. Fetch responses don't allow you to read these twice, so it's best if we memoize the results to prevent users from running into this. ```javascript const request = new FetchRequest("post", url) const response = await request.perform() await response.text await response.text // => Failed to execute 'text' on 'Response': body stream already read ``` Most importantly, we need memoization so you can still read the response text after the Turbo Stream messages are read and rendered. ``` const request = new FetchRequest("post", url, { responseKind: "turbo-stream" }) const response = await request.perform() await response.text // => Failed to execute 'text' on 'Response': body stream already read ``` Fixes #19
2 parents 2518291 + 6aba50e commit 775f1eb

File tree

1 file changed

+3
-3
lines changed

1 file changed

+3
-3
lines changed

src/fetch_response.js

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -31,22 +31,22 @@ export class FetchResponse {
3131

3232
get html () {
3333
if (this.contentType.match(/^(application|text)\/(html|xhtml\+xml)$/)) {
34-
return this.response.text()
34+
return this.text
3535
}
3636

3737
return Promise.reject(new Error(`Expected an HTML response but got "${this.contentType}" instead`))
3838
}
3939

4040
get json () {
4141
if (this.contentType.match(/^application\/json/)) {
42-
return this.response.json()
42+
return this.responseJson || (this.responseJson = this.response.json())
4343
}
4444

4545
return Promise.reject(new Error(`Expected a JSON response but got "${this.contentType}" instead`))
4646
}
4747

4848
get text () {
49-
return this.response.text()
49+
return this.responseText || (this.responseText = this.response.text())
5050
}
5151

5252
get isTurboStream () {

0 commit comments

Comments
 (0)