Hooks
useDataState
Hook for managing loading, success, and error states in data-fetching workflows.
useDataState
A state machine hook for managing the lifecycle of data-fetching operations with loading, success, and error states.
Import
import { useDataState } from '@mks2508/mks-ui/react';Basic Usage
function UserProfile({ userId }) {
const { state, load, reset } = useDataState();
useEffect(() => {
load(async () => {
const res = await fetch(`/api/users/${userId}`);
return res.json();
});
}, [userId, load]);
if (state.status === 'loading') return <p>Loading...</p>;
if (state.status === 'error') return <p>Error: {state.error.message}</p>;
if (state.status === 'success') return <p>Hello, {state.data.name}</p>;
return null;
}States
| Status | Properties | Description |
|---|---|---|
idle | — | Initial state, no request made |
loading | — | Request in progress |
success | data: T | Request completed successfully |
error | error: Error | Request failed |
With Retry
const { state, load } = useDataState();
const fetchData = useCallback(() => {
load(async () => {
const res = await fetch('/api/data');
if (!res.ok) throw new Error('Failed');
return res.json();
});
}, [load]);
// Retry on error
if (state.status === 'error') {
return <Button onClick={fetchData}>Retry</Button>;
}API Reference
Return Value
| Property | Type | Description |
|---|---|---|
state | DataState<T> | Current state object |
load | (fn: () => Promise<T>) => void | Execute an async operation |
reset | () => void | Reset to idle state |