kit icon indicating copy to clipboard operation
kit copied to clipboard

svelte fetch causes api results to be cached

Open sacrosanctic opened this issue 1 year ago • 2 comments

Describe the bug

Using svelte fetch causes the same data to be returned.

// +page.ts
export const load = async ({ fetch }) => {
	const values: string[] = [];

	for (let i = 0; i < 5; i++) {
		const res = await fetch('https://api.chucknorris.io/jokes/random');
		const { value } = await res.json();
		values.push(value);
	}

	return { values };
};
<script lang="ts">
	export let data;
	const values = data.values;
</script>

{#each values as value, index}
	<h1>{index}: {value}</h1>
{/each}

Reproduction

npx degit https://github.com/sacrosanctic/bug-with-svelte-fetch
npm i
npm run dev

routes/a/+page.svelte should demonstrate the bug

Logs

No response

System Info

.

Severity

annoyance

Additional Information

https://discord.com/channels/457912077277855764/1251255888598274138

related conversation on discord

sacrosanctic avatar Jun 14 '24 20:06 sacrosanctic

I had a similar issue when I fetched the same url with an OPTION request and then a GET request. The response was fine initially on the server side, but on the client-side resulted in the OPTION response being returned for both the OPTION and GET requests. This then prevented the render on the client side as the GET response contained OPTION response data. I imagine the fix for the above issue would also resolve the issue I have seen. My work around was to use a window.fetch rather than svelte kit fetch for the OPTIONS request in order to avoid caching the OPTIONS response.

mbsk78 avatar Aug 06 '24 23:08 mbsk78