Skip to content

Commit

Permalink
Reuse request so that a ReabableStream body does not become disturbed (
Browse files Browse the repository at this point in the history
  • Loading branch information
agadzik authored and AndyPengc12 committed Apr 15, 2024
1 parent 0e32957 commit c1033b7
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 1 deletion.
8 changes: 7 additions & 1 deletion packages/react/src/ReactFetch.js
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,13 @@ if (enableCache && enableFetchInstrumentation) {
url = resource;
} else {
// Normalize the request.
const request = new Request(resource, options);
// if resource is not a string or a URL (its an instance of Request)
// then do not instantiate a new Request but instead
// reuse the request as to not disturb the body in the event it's a ReadableStream.
const request =
typeof resource === 'string' || resource instanceof URL
? new Request(resource, options)
: resource;
if (
(request.method !== 'GET' && request.method !== 'HEAD') ||
// $FlowFixMe[prop-missing]: keepalive is real
Expand Down
16 changes: 16 additions & 0 deletions packages/react/src/__tests__/ReactFetch-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -135,6 +135,22 @@ describe('ReactFetch', () => {
expect(fetchCount).toBe(1);
});

// @gate enableFetchInstrumentation && enableCache
it('can dedupe fetches using URL and not', async () => {
const url = 'http://example.com/';
function Component() {
const response = use(fetch(url));
const text = use(response.text());
const response2 = use(fetch(new URL(url)));
const text2 = use(response2.text());
return text + ' ' + text2;
}
expect(await render(Component)).toMatchInlineSnapshot(
`"GET ${url} [] GET ${url} []"`,
);
expect(fetchCount).toBe(1);
});

it('can opt-out of deduping fetches inside of render with custom signal', async () => {
const controller = new AbortController();
function useCustomHook() {
Expand Down

0 comments on commit c1033b7

Please sign in to comment.