@mks2508/mks-ui
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

StatusPropertiesDescription
idleInitial state, no request made
loadingRequest in progress
successdata: TRequest completed successfully
errorerror: ErrorRequest 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

PropertyTypeDescription
stateDataState<T>Current state object
load(fn: () => Promise<T>) => voidExecute an async operation
reset() => voidReset to idle state