asyncState

Category States

A reactive state that handles the loading and error states of a promise.

Demo

Loading the recipe with id 1...

Usage

<script>
	import { asyncState } from '@sv-use/core';
 
	const recipe = asyncState(
		fetch(`https://dummyjson.com/recipes/1`)
            .then((res) => res.json()),
		null
	);
</script>

Examples

A basic example where you wait for the value to be resolved.

<script>
	import { asyncState } from '@sv-use/core';
 
	const recipe = asyncState(
		fetch(`https://dummyjson.com/recipes/1`)
            .then((res) => res.json()),
		null
	);
</script>
 
{#if recipe.isLoading}
	<p>Loading your recipe...</p>
{:else}
	<pre>{JSON.stringify(recipe.current, null, 4)}</pre>
{/if}

A more advanced usage where the recipe is fetched again when the id changes and shows the last result before swapping instead of showing the loading tag.

Note that you have to set immediate to false if you are using a function that depends on arguments for the promise parameter, and then manually call the execute function.

<script>
	import { asyncState } from '@sv-use/core';
 
	let id = $state(1);
	const recipe = asyncState((id) => {
        return fetch(`https://dummyjson.com/recipes/${id}`)
                .then((res) => res.json());
    }, null, { immediate: false });
 
	$effect(() => {
		recipe.execute(id);
	});
</script>
 
{#if !recipe.current}
	<p>Loading your recipe...</p>
{:else}
	<pre>{JSON.stringify(recipe.current, null, 4)}</pre>
	<button onclick={() => id++}>Next recipe</button>
{/if}
Type definitions
type AsyncStateOptions<Data = unknown> = {
    /**
     * Whether to run the promise immediately or not.
     *
     * Set this to `false` if your promise is a function that depends on arguments.
     * @default true
     */
    immediate?: boolean;
    /**
     * Whether to reset the state to the initial value when the promise is executed.
     * @default false
     */
    resetOnExecute?: boolean;
    /**
     * A callback for when the promise resolves successfully.
     * @param data The data returned by the promise.
     * @default () => {}
     */
    onSuccess?: (data: Data) => void;
    /**
     * A callback for when the promise rejects.
     * @param error The error returned by the promise.
     * @default () => {}
     */
    onError?: (error: unknown) => void;
};
type AsyncStateReturn<Data = unknown, Parameters extends unknown[] = unknown[]> = {
    /** Whether the state is ready or not. */
    readonly isReady: boolean;
    /** Whether the state is loading or not. */
    readonly isLoading: boolean;
    /** The current value of the state. */
    current: Data;
    /** The error of the state if any. */
    error: unknown | null;
    /**
     * Executes the promise programatically.
     *
     * Useful when
     *  * the promise is a function that depends on arguments.
     *  * you want to poll data at intervals.
     */
    execute: (...args: Parameters) => Promise<void>;
};
/**
 * A reactive state that handles the loading and error states of a promise.
 * @param promise The promise to handle.
 * @param initial The initial value of the state.
 * @param options Additional options to customize the behavior.
 * @see https://svelte-librarian.github.io/sv-use/docs/core/states/async-state
 */
export declare function asyncState<Data = unknown, Parameters extends unknown[] = unknown[]>(promise: Promise<Data> | ((...args: Parameters) => Promise<Data>), initial: Data, options?: AsyncStateOptions<Data>): AsyncStateReturn<Data, Parameters>;
export {};

Sources