-
Let's suppose we load a Desired flow: when a page ID changes - check if we have a cache and set it while fetching the final content. <script lang="ts">
let { pageId } : { pageId: string } = $props();
async function getPageContent(pageId: number): Promise<string> {
// Wait for 3 seconds before returning the content
await new Promise((resolve) => setTimeout(resolve, 3000));
return pageId;
}
let pageContent = $derived.by(async () => {
return await getPageContent(pageId);
});
// @TODO: would it be possible to set pageContent to
// something before we resolve getPageContent?
</script>
<h1>Page {pageId} is selected</h1>
{#await pageContent}
<strong>Loading...</strong>
{:then content }
<strong>{content}</strong>
{/await}
<br /><br />
<small>We're waiting for 3 seconds to "load"
content of the page after its id changes.</small> |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 6 replies
-
You can store the data in a local <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 handle types) |
Beta Was this translation helpful? Give feedback.
You can store the data in a local
$state
and update that asynchronously. E.g.Playground (did not handl…