A lightweight, type-safe library for managing async state
npm install async-xtate
A lightweight, type-safe library for managing async state in TypeScript applications.
- 🚀 Type-safe async state management
- 📦 Zero dependencies
- 🎯 Simple and intuitive API
- 🔄 Support for all async states (initial, loading, success, error, refetch)
- 🛠️ Built with TypeScript
``bash`
npm install async-xtateor
yarn add async-xtateor
pnpm add async-xtateor
bun add async-xtate
`typescript
import {
makeAsyncSuccessState,
makeAsyncErrorState,
makeAsyncLoadingState,
makeRefetchState,
makeInitialState,
type AsyncState
} from 'async-xtate';
// Define your data and error types
type UserData = { name: string; email: string };
type UserError = string;
// Create different states
const successState = makeAsyncSuccessState
name: 'John Doe',
email: 'john@example.com'
});
const errorState = makeAsyncErrorState
'Failed to fetch user',
{ name: 'John Doe', email: 'john@example.com' }
);
const loadingState = makeAsyncLoadingState
const refetchState = makeRefetchState
{ name: 'John Doe', email: 'john@example.com' }
);
const initialState = makeInitialState
`
- AsyncSuccessState: Represents a successful async operationAsyncErrorState
- : Represents a failed async operationAsyncLoadingState
- : Represents a loading stateAsyncRefetchState
- : Represents a refetching stateAsyncInitialState
- : Represents the initial stateAsyncState
- : Union type of all possible states
- makeAsyncSuccessState(data: Data): Creates a success statemakeAsyncErrorState
- : Creates an error statemakeAsyncLoadingState(data?: Data, error?: Err)
- : Creates a loading statemakeRefetchState(data?: Data, error?: Err)
- : Creates a refetch statemakeInitialState(data?: Data, error?: Err)
- : Creates an initial state
The library is fully type-safe, providing TypeScript with all the information it needs to ensure type correctness:
`typescript
const state: AsyncState
name: 'John Doe',
email: 'john@example.com'
});
// TypeScript knows the exact shape of the state
if (state.status === 'success') {
console.log(state.data.name); // ✅ TypeScript knows this is safe
}
``
Contributions are welcome! Please feel free to submit a Pull Request.
MIT © Roberto Ríos