Async

One convention for loading, error, empty and ready states. Works with TanStack Query results or useAsync.

Status: stable. Category: Patterns.

import { Async, EmptyState, ErrorState, LoadingState } from '@glyphui/ui'

Exports: Async, useAsync, EmptyState, ErrorState, LoadingState, stateStyles.

Notes

  • Any object with status, data, error and refetch works, including useQuery() results.
  • ErrorState has role="alert"; LoadingState has role="status".

Async props

PropTypeDefaultDescription
children (required)(data: NonNullable<T>) => ReactNodeRendered once data is ready and not empty.
result (required)AsyncResult<T>
emptyReactNode
errorReactNode | ((error: unknown, retry: (() => unknown)) => ReactNode)
isEmpty((data: NonNullable<T>) => boolean)(data: unknown) => Array.isArray(data) && data.length === 0Treat ready data as empty. Defaults to: an empty array.
loadingReactNode

Example: With useAsync

import { Async, Button, useAsync } from '@glyphui/ui'
import { useState } from 'react'

const projects = ['Website redesign', 'Billing v2', 'Mobile onboarding']

function fetchProjects(fail: boolean): Promise<string[]> {
  return new Promise((resolve, reject) =>
    setTimeout(
      () => (fail ? reject(new Error('The projects service timed out.')) : resolve(projects)),
      900,
    ),
  )
}

export default function Example() {
  const [fail, setFail] = useState(false)
  const result = useAsync(() => fetchProjects(fail), [fail])
  return (
    <div className="grid gap-3">
      <Button
        variant="outline"
        size="sm"
        className="justify-self-start"
        onClick={() => setFail((f) => !f)}
      >
        {fail ? 'Load successfully' : 'Simulate an error'}
      </Button>
      <Async result={result}>
        {(items) => (
          <ul className="grid gap-1 text-small">
            {items.map((name) => (
              <li key={name}>{name}</li>
            ))}
          </ul>
        )}
      </Async>
    </div>
  )
}

Example: State components

Use them directly anywhere a screen can be empty or fail.

import { Button, EmptyState, ErrorState, LoadingState } from '@glyphui/ui'
import { FolderPlus } from 'lucide-react'

export default function Example() {
  return (
    <div className="grid gap-4 sm:grid-cols-3">
      <EmptyState
        icon={<FolderPlus />}
        title="No projects yet"
        description="Create a project to start tracking work."
        action={<Button size="sm">New project</Button>}
      />
      <ErrorState error={new Error('Network request failed.')} onRetry={() => {}} />
      <LoadingState label="Loading projects…" />
    </div>
  )
}

Live page: https://glyphui.xyz/components/async