Async
A zero-boilerplate wrapper that drives the right UI for every stage of an async data fetch. It manages aria-busy, aria-live, and role automatically so screen readers always stay informed.
status defaults to success, so default slotted content is visible unless you explicitly set another state.
Features
- 🔄 5 statuses:
idle,loading,empty,error,success - 💀 Default skeleton loading state — no setup needed
- 📭 Built-in empty state with configurable label and description
- ⚠️ Built-in error state with optional retry button
- 🎰 Fully slottable — replace any built-in view with your own content
- ♿ Automatic ARIA —
aria-busy,aria-live,role="alert"managed for you
Source Code
View Source Code
ts
import { define, prop, html, signal, type Signal, onMounted, when } from '@vielzeug/craftit';
import '../../content/icon/icon';
import { reducedMotionMixin } from '../../styles';
import '../skeleton/skeleton';
import componentStyles from './async.css?inline';
export type AsyncStatus = 'idle' | 'loading' | 'empty' | 'error' | 'success';
export type BitAsyncEvents = {
retry: void;
};
export type BitAsyncProps = {
'empty-description'?: string;
'empty-label'?: string;
'error-description'?: string;
'error-label'?: string;
retryable?: boolean;
status?: AsyncStatus;
};
/**
* A container for handling asynchronous states (loading, empty, error, success).
* Simplifies data fetching UI by providing consistent fallbacks.
*
* @element bit-async
*
* @attr {string} status - current state: 'idle' | 'loading' | 'empty' | 'error' | 'success' (default: 'success')
* @attr {boolean} retryable - show retry button in error state (default: false)
* @attr {string} empty-label - title for empty state (default: 'No content yet')
* @attr {string} empty-description - optional text for empty state
* @attr {string} error-label - title for error state (default: 'Something went wrong')
* @attr {string} error-description - optional text for error state
*
* @fires retry - when the retry button is clicked
*
* @slot - default content shown in 'success' state
* @slot loading - custom loading UI (overrides default skeletons)
* @slot empty - custom empty UI (overrides default icon/label)
* @slot error - custom error UI (overrides default icon/label)
*
* @cssprop --async-color - Text/icon color used by default async state content
* @cssprop --async-gap - Vertical spacing between icon, title, description, and actions
* @cssprop --async-icon-size - Icon size for built-in loading/empty/error visuals
* @cssprop --color-contrast-500 - Secondary description text color
* @cssprop --color-contrast-700 - Primary heading text color for neutral states
* @cssprop --color-error-500 - Base error color for the default error icon
* @cssprop --color-error-600 - Strong error color for titles and emphasis
* @cssprop --color-error-700 - Deep error color for high-contrast error text
* @cssprop --font-medium - Font weight used by default state descriptions
* @cssprop --font-semibold - Font weight used by default state titles
* @cssprop --leading-relaxed - Line-height for default state descriptions
* @cssprop --rounded-md - Corner radius for default state surfaces and placeholders
* @example
* ```html
* <bit-async status=${status} @retry=${fetchData}>
* <ul>...list items...</ul>
* </bit-async>
*
* <!-- Custom empty slot -->
* <bit-async status="empty">
* <div slot="empty">
* <img src="/no-results.svg" alt="" />
* <p>Try adjusting your filters.</p>
* </div>
* </bit-async>
* ```
*/
export const ASYNC_TAG = define<BitAsyncProps, BitAsyncEvents>('bit-async', {
props: {
'empty-description': undefined,
'empty-label': 'No content yet',
'error-description': undefined,
'error-label': 'Something went wrong',
retryable: false,
status: prop.oneOf(['idle', 'loading', 'empty', 'error', 'success'] as const, 'success'),
},
setup(props, { emit, host }) {
const hasLoadingSlot = signal(false);
const hasEmptySlot = signal(false);
const hasErrorSlot = signal(false);
const updateNamedSlotPresence = () => {
const children = Array.from(host.el.children);
hasLoadingSlot.value = children.some((child) => child.getAttribute('slot') === 'loading');
hasEmptySlot.value = children.some((child) => child.getAttribute('slot') === 'empty');
hasErrorSlot.value = children.some((child) => child.getAttribute('slot') === 'error');
};
updateNamedSlotPresence();
const mount = () => {
updateNamedSlotPresence();
const observer = new MutationObserver(() => updateNamedSlotPresence());
observer.observe(host.el, { attributeFilter: ['slot'], attributes: true, childList: true, subtree: true });
return () => observer.disconnect();
};
// Keep host accessibility state in sync with async status.
host.bind({
attr: {
ariaBusy: () => (props.status!.value === 'loading' ? 'true' : 'false'),
ariaLabel: () => (props.status!.value === 'loading' ? 'Loading…' : null),
ariaLive: () => (props.status!.value === 'error' ? 'assertive' : 'polite'),
},
});
const renderText = (className: 'title' | 'description', text: Signal<string | undefined> | undefined) => () =>
text?.value ? html`<p class="${className}">${text}</p>` : '';
const renderDefaultState = ({
action,
description,
icon,
label,
role,
stateClass,
}: {
action?: () => unknown;
description: Signal<string | undefined> | undefined;
icon: string;
label: Signal<string | undefined> | undefined;
role: 'alert' | 'status';
stateClass: 'empty-state' | 'error-state';
}) => html`
<div class="${stateClass}" role="${role}">
<div class="icon">
<bit-icon name="${icon}" size="100%" stroke-width="1.75" aria-hidden="true"></bit-icon>
</div>
${renderText('title', label)} ${renderText('description', description)} ${action?.()}
</div>
`;
const renderLoadingFallback = () => html`
<div class="loading-default" aria-hidden="true">
<bit-skeleton variant="text" lines="1" width="40%"></bit-skeleton>
<bit-skeleton variant="text" lines="3" width="100%"></bit-skeleton>
<bit-skeleton variant="text" lines="1" width="60%"></bit-skeleton>
</div>
`;
const renderSuccess = () => html`
<div class="region" role="presentation">
<slot></slot>
</div>
`;
const renderByStatus = () => {
const status = props.status!.value;
if (status === 'idle') {
return html`<div class="region" role="presentation"></div>`;
}
if (status === 'loading') {
return html`
<div class="region" role="status">
${when(hasLoadingSlot, () => html`<slot name="loading"></slot>`, renderLoadingFallback)}
</div>
`;
}
if (status === 'empty') {
return html`
<div class="region">
${when(
hasEmptySlot,
() => html`<slot name="empty"></slot>`,
() =>
renderDefaultState({
description: props['empty-description'],
icon: 'inbox',
label: props['empty-label'],
role: 'status',
stateClass: 'empty-state',
}),
)}
</div>
`;
}
if (status === 'error') {
return html`
<div class="region">
${when(
hasErrorSlot,
() => html`<slot name="error"></slot>`,
() =>
renderDefaultState({
action: () =>
when(
() => Boolean(props.retryable!.value),
() => html`
<button class="retry-btn" type="button" @click=${() => emit('retry')}>
<bit-icon name="refresh-cw" size="1em" stroke-width="2" aria-hidden="true"></bit-icon>
Try again
</button>
`,
),
description: props['error-description'],
icon: 'triangle-alert',
label: props['error-label'],
role: 'alert',
stateClass: 'error-state',
}),
)}
</div>
`;
}
return renderSuccess();
};
onMounted(mount);
return () => html`${() => renderByStatus()}`;
},
styles: [reducedMotionMixin, componentStyles],
});Basic Usage
html
<bit-async status="loading"></bit-async>
<script type="module">
import '@vielzeug/buildit/async';
import '@vielzeug/buildit/skeleton';
</script>Switch status from your data layer:
js
const el = document.querySelector('bit-async');
async function loadData() {
el.status = 'loading';
try {
const data = await fetch('/api/items').then((r) => r.json());
el.status = data.length ? 'success' : 'empty';
} catch {
el.status = 'error';
}
}Status: Loading
The default loading view renders a skeleton stack automatically. No slot required.
Custom Loading Slot
Status: Empty
Custom Empty Slot
Status: Error
Custom Error Slot
Status: Success
Retry
Add retryable to show a built-in retry button in the error state. Listen for the retry event to re-trigger your fetch.
Composing with bit-card
Composing with bit-table
Status values
status | What renders | aria-busy | aria-live |
|---|---|---|---|
idle | nothing (empty region) | false | polite |
loading | loading slot or skeleton stack | true | polite |
empty | empty slot or built-in empty state | false | polite |
error | error slot or built-in error state | false | assertive |
success | default slot (your content) | false | polite |
Props
| Attribute | Type | Default | Description |
|---|---|---|---|
status | AsyncStatus | 'success' | Current data-fetch status |
empty-label | string | 'No content yet' | Heading for the built-in empty state |
empty-description | string | — | Description below the empty-state heading |
error-label | string | 'Something went wrong' | Heading for the built-in error state |
error-description | string | — | Description below the error-state heading |
retryable | boolean | false | Show retry button in the built-in error state |
Events
| Event | Detail | Description |
|---|---|---|
retry | — | Fired when the built-in retry button is clicked |
Slots
| Slot | Description |
|---|---|
| (default) | Rendered when status="success" |
loading | Replaces the built-in skeleton stack during loading |
empty | Replaces the built-in empty state illustration |
error | Replaces the built-in error view |
CSS Custom Properties
| Property | Default | Description |
|---|---|---|
--async-color | --color-contrast-500 | Icon/text color for built-in states |
--async-icon-size | var(--size-12) | Icon size in built-in empty/error views |
--async-gap | var(--size-3) | Gap between elements in built-in views |
Accessibility
bit-async manages ARIA on the host element automatically:
aria-busy="true"while status isloading— screen readers announce the busy region.aria-live="assertive"in theerrorstate — error messages interrupt immediately.aria-live="polite"in all other states — updates are announced after the current action.- The built-in error region uses
role="alert"for immediate screen reader pickup. - The built-in loading and empty regions use
role="status"for polite announcements. - The retry button is typed
type="button"to prevent accidental form submission.