Skip to content

How to set a state twice in async after props change? #13985

Answered by brunnerh
mitkury asked this question in Q&A
Discussion options

You must be logged in to vote

You can store the data in a local $state and update that asynchronously. E.g.

<script>
	// ...

	let storage = {}; // local storage stand-in

	let pageContent = $derived.by(async () => {
		const cached = storage[pageId];
		const page = $state({
			content: cached == null
				? undefined
				: (cached + ' (from cache)'),
		});

		const fetchContent = getPageContent(pageId)
				.then(c => storage[pageId] = page.content = c);

		// nothing to show => show #await placeholder
		if (cached == null)
			await fetchContent;

		return page;
	});
</script>

<!-- ... -->

{#await pageContent}
	<strong>Loading...</strong>
{:then page}
	<strong>{page.content}</strong>
{/await}

Playground (did not handl…

Replies: 1 comment 6 replies

Comment options

You must be logged in to vote
6 replies
@david-plugge
Comment options

@brunnerh
Comment options

@david-plugge
Comment options

@mitkury
Comment options

@brunnerh
Comment options

Answer selected by mitkury
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
3 participants