resourceState
Signature
resourceState<T>(selector: Selector<T>, store?: Store): ResourceState<T>valdres-svelte Async selector with loading and error state
Consumes a possibly-async selector as a reactive { current, loading, error } box. Core erases asyncness, so fromState(sel).current may be T | Promise<T>; resourceState does the runtime promise detection for you and tracks settlement. While pending, loading is true and current is undefined; on resolve, current holds the value; on reject, error holds the reason. A dependency change re-enters the pending state.
Usage
<script lang="ts">
import { selector } from "valdres"
import { resourceState } from "valdres-svelte"
const userSelector = selector(() => fetch("/api/me").then(r => r.json()))
const user = resourceState(userSelector)
</script>
{#if user.loading}
<p>Loading…</p>
{:else if user.error}
<p>Failed: {String(user.error)}</p>
{:else}
<p>Hello {user.current?.name}</p>
{/if}
When you'd rather await than branch on flags, fromState plus Svelte's {#await} block works directly on the T | Promise<T> value (fromState(sel).current, not the resourceState box above):
<script lang="ts">
import { fromState } from "valdres-svelte"
import { userSelector } from "$lib/state"
const user = fromState(userSelector)
</script>
{#await user.current then u}
<p>Hello {u.name}</p>
{/await}
Returns
| Member | Type | Description |
|---|---|---|
current | T | undefined | Resolved value, or undefined while pending or errored |
loading | boolean | true while the selector's promise is pending |
error | unknown | The rejection reason, if the promise rejected |