useAsyncState

Reactive async state. Will not block your setup function and will trigger changes once the promise is ready.

Usage

<script>
  import axios from 'axios'
  import { useAsyncState } from '@svelte-use/core'

  const { state, isReady } = useAsyncState(
    axios
      .get('https://jsonplaceholder.typicode.com/todos/1')
      .then((res) => res.data),
    { id: null },
  )
</script>

Type Declarations

export interface AsyncStateOptions {
  /**
   * Delay for executeing the promise. In milliseconds.
   *
   * @default 0
   */
  delay?: number
  /**
   * Execute the promise right after the function is invoked.
   * Will apply the delay if any.
   *
   * When set to false, you will need to execute it manually.
   *
   * @default true
   */
  immediate?: boolean
  /**
   * Callback when error is caught.
   */
  onError?: (e: unknown) => void
  /**
   * Sets the state to initialState before executing the promise.
   *
   * This can be useful when calling the execute function more than once (for
   * example, to refresh data). When set to false, the current state remains
   * unchanged until the promise resolves.
   *
   * @default true
   */
  resetOnExecute?: boolean
}
/**
 * Reactive async state. Will not block your setup function and will triggers changes once
 * the promise is ready.
 *
 * @see https://svelte-use.vercel.app/core/useAsyncState
 * @param promise         The promise / async function to be resolved
 * @param initialState    The initial state, used until the first evaluation finishes
 * @param options
 */
export declare function useAsyncState<T>(
  promise: Promise<T> | PromiseFn<T>,
  initialState: T,
  options?: AsyncStateOptions
): {
  state: Writable<T>
  isReady: Writable<boolean>
  error: Writable<unknown>
  execute: (delay?: number, ...args: any[]) => Promise<void>
}
export declare type UseAsyncStateReturn = ReturnType<typeof useAsyncState>

Source

SourceDemoDocs