Skip to content

Commit 6b34122

Browse files
PatrickGdummdidummRich-Harris
authored
fix: use correct cache result when fetching same url multiple times (#12355)
* Added test * Fix * Changeset * Update packages/kit/src/runtime/client/fetcher.js Co-authored-by: Simon H <[email protected]> --------- Co-authored-by: Simon H <[email protected]> Co-authored-by: Rich Harris <[email protected]>
1 parent ece3906 commit 6b34122

File tree

6 files changed

+37
-0
lines changed

6 files changed

+37
-0
lines changed

.changeset/seven-gorillas-protect.md

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
"@sveltejs/kit": patch
3+
---
4+
5+
fix: use correct cache result when fetching same url multiple times

packages/kit/src/runtime/client/fetcher.js

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -90,6 +90,7 @@ export function initial_fetch(resource, opts) {
9090

9191
const script = document.querySelector(selector);
9292
if (script?.textContent) {
93+
script.remove(); // In case multiple script tags match the same selector
9394
let { body, ...init } = JSON.parse(script.textContent);
9495

9596
const ttl = script.getAttribute('data-ttl');
Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
/** @type {import('@sveltejs/kit').Load} */
2+
export async function load({ fetch, url }) {
3+
const results = [];
4+
5+
for (let i = 0; i < 3; i++) {
6+
const res = await fetch(`${url.origin}/load/fetch-same-url/data.json`);
7+
const json = await res.json();
8+
results.push(json.result);
9+
}
10+
11+
return { results };
12+
}
Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
<script>
2+
export let data;
3+
</script>
4+
5+
<h1>the result is {data.results.join(',')}</h1>
Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
import { json } from '@sveltejs/kit';
2+
3+
let result = 0;
4+
5+
/** @type {import('./$types').RequestHandler} */
6+
export function GET() {
7+
result++;
8+
return json({ result });
9+
}

packages/kit/test/apps/basics/test/client.test.js

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -239,6 +239,11 @@ test.describe('Load', () => {
239239
expect(requests.filter((r) => !r.includes('/__route.js'))).toEqual([]);
240240
});
241241

242+
test('use correct cache result when fetching same url multiple times', async ({ page }) => {
243+
await page.goto('/load/fetch-same-url');
244+
expect(await page.textContent('h1')).toBe('the result is 1,2,3');
245+
});
246+
242247
test('permits 3rd party patching of fetch in universal load functions', async ({ page }) => {
243248
/** @type {string[]} */
244249
const logs = [];

0 commit comments

Comments
 (0)