How to show loading state when remote function re-fetches on URL param change #14945
Replies: 1 comment
|
The For the re-fetch indicator you want the query's own state instead of <script lang="ts">
import { getPosts } from './data.remote.js';
let { params } = $props();
// store the query in a variable, don't inline it
const posts = $derived(getPosts(params));
</script>
{#if posts.loading}
<p>Refreshing…</p>
{/if}
{#if posts.error}
<p>Failed: {posts.error.message}</p>
{:else}
<ul>
{#each posts.current ?? [] as post}
<li>{post.title}</li>
{/each}
</ul>
{/if}The one thing that'll bite you: assign the query to a variable first ( Trade-off worth knowing: |
Uh oh!
There was an error while loading. Please reload this page.
Hi! I’m learning SvelteKit and remote functions, and I can’t figure out this problem:
Context: I’m building a simple list of posts with pagination. The current page is stored in the URL as search params. I get the params using
useSearchParamsfrom the Runed library and pass them into the remote function. The remote function is wrapped in$derived, so whenever the params update, the remote function re-fetches the data. Also I am usingawaitas it is recommended in the docs and required (If I understand it right) for SSR to work. Also it is cleaner as I don't need to writeifbranches everywhere and use<svelte:boundary>. Here is relevant code:Problem: During the refetch I want to show a loading indicator to the user. I tried using the pending block inside
<svelte:boundary>, but that only works on the initial load (as stated in the docs). I also tried checkingremoteFunction().loading, but that doesn’t work either because it stays false even while the data is being fetched. Only time it.loadingworks is, when not using await at all and only use.loading.error.currentnotation. But then I cannot get the advantages of usingawaitform: SSR (if I don't use pending snippet), pending snippet and that I have old data until the refetch is resolved (which is very useful), while with.current, data gets replaced withundefineduntil the refetch is resolved.Question: What is the correct way to indicate that a remote function is refetching when the URL search parameters change? Ideally using await form? I just want to show some indicator and deactivate pagination buttons to not cause confusion for the user.
Here is demo repo: https://github.com/davidbaranek/sveltekit-demo
Sorry if this has already been answered, but I wasn’t able to find anything useful. Thanks for any advice!
All reactions