saga-toolkit
v2.5.0
Published
An extension for redux-toolkit that allows sagas to resolve async thunk actions.
Downloads
674
Maintainers
Readme
Saga Toolkit
Seamlessly integrate Redux Toolkit with Redux Saga.
saga-toolkit acts as a bridge between Redux Toolkit's createAsyncThunk and Redux Saga. It allows you to dispatch actions that trigger Sagas, while retaining the ability to await the result (promise) directly in your components or thunks.
If you love the "fire-and-forget" nature of Sagas for complex flows but miss the convenience of await dispatch(action) for simple request/response patterns (like form submissions), this library is for you.
Features
- 🤝 Bridge Pattern: Connects
createAsyncThunk(RTK) withtakeEvery/takeLatest(Saga). - 🔄 Promise Support:
awaityour Saga actions in React components. - ⚡ Reduce Boilerplate: Easily handle loading/success/error states in slices using standard RTK patterns.
- 🛑 Real Cancellation:
promise.abort()cancels the running Saga (andtakeLatestAsyncaborts superseded requests). - 🧭 Type-safe: pass the action creator itself to the effects — action and return types are inferred and enforced.
- 🚨 No silent hangs: if you forget to register a watcher saga, the promise rejects with an actionable error instead of pending forever.
💡 Why saga-toolkit?
Modernize your Sagas.
The biggest criticism of Redux Saga has always been its verbosity. saga-toolkit cuts through the noise.
- Zero Boilerplate: Forget about manually defining
_REQUEST,_SUCCESS, and_FAILUREaction types.createSagaActionhandles the lifecycle elegantly. - The "Glue" You Needed: While libraries like React Query are great for fetching, Sagas are still unbeatable for complex background orchestration, race conditions, and heavy business logic.
saga-toolkitis the perfect glue to connect that logic to your modern UI. - Best of Both Worlds: Keep the power of Generators but gain the ease of
awaitand standard Redux Toolkit patterns.
"The reason I’m still sticking with Sagas in mid-to-large projects is a matter of 'architectural safety.' With Sagas, I never have to worry about a product feature becoming so twisted (complex cancellations, racing multiple async flows, or multi-step orchestration) that the tool can't handle it. It’s that security of knowing I won’t hit a wall regardless of how 'insane' the requirements get."
🎮 Try the Example App
This project includes a fully functional Todo App built with Vite, React 18, and TypeScript to demonstrate:
createSagaAction(AsyncThunk bridge)takeEveryAsync(Awaitable actions)takeLatestAsync(Cancellable search)takeAggregateAsync(De-duplicated refresh)putAsync(Saga composition)
Run Locally
cd example
npm install
npm run devTry Online (StackBlitz)
Installation
npm install saga-toolkitPeer Dependencies: @reduxjs/toolkit, redux-saga
Usage Guide
1. Create a "Saga Action"
Instead of createAsyncThunk or standard action creators, use createSagaAction. This creates an Async Thunk that returns a promise which your Saga will resolve or reject.
/* slice.ts */
import { createSlice, PayloadAction } from '@reduxjs/toolkit'
import { createSagaAction } from 'saga-toolkit'
interface User {
id: string
name: string
}
const name = 'users'
// Define the action: <Returned, ThunkArg>
export const fetchUser = createSagaAction<User, string>(`${name}/fetchUser`)
const slice = createSlice({
name,
initialState: { data: null as User | null, loading: false },
extraReducers: (builder) => {
builder
.addCase(fetchUser.pending, (state) => { state.loading = true })
.addCase(fetchUser.fulfilled, (state, action: PayloadAction<User>) => {
state.loading = false
state.data = action.payload
})
},
})
export default slice.reducer2. Connect to a Saga
Use takeEveryAsync (or takeLatestAsync, etc.) to listen for the action. Pass the action creator itself — the effect listens on its pending type automatically, infers the action type, and even enforces that your saga returns the declared result type (User here):
/* sagas.ts */
import { call } from 'redux-saga/effects'
import { takeEveryAsync, SagaPendingAction } from 'saga-toolkit'
import { fetchUser } from './slice'
function* fetchUserSaga(action: SagaPendingAction<typeof fetchUser>) {
const userId = action.meta.arg // typed as string
// The return value here resolves the promise —
// and must be a User, or TypeScript will complain!
const user: User = yield call(API.getUser, userId)
return user
}
export default function* rootSaga() {
yield takeEveryAsync(fetchUser, fetchUserSaga)
}Prefer classic patterns?
takeEveryAsync(fetchUser.pending.type, fetchUserSaga)still works exactly as before.
3. Dispatch and Await in Component
Option A: The Easy Way (Recommended)
Use the useSagaActions hook to automatically bind dispatch and unwrap promises.
/* UserComponent.tsx */
import { useSagaActions } from 'saga-toolkit'
import { fetchUser } from './slice'
const UserComponent = ({ id }: { id: string }) => {
// Automatically binds dispatch AND unwraps promises!
const actions = useSagaActions({ fetchUser })
const handleFetch = async () => {
try {
// Clean awaitable call!
const user = await actions.fetchUser(id)
console.log('Got user:', user)
} catch (error) {
console.error('Failed to fetch:', error)
}
}
return <button onClick={handleFetch}>Load User</button>
}Option B: The Manual Way (Classic Redux)
If you prefer standard Redux patterns or need to access the raw action object, you can dispatch manually.
/* UserComponent.tsx */
import { useDispatch } from 'react-redux'
import { unwrapResult } from '@reduxjs/toolkit'
import { fetchUser } from './slice'
const UserComponent = ({ id }: { id: string }) => {
const dispatch = useDispatch()
const handleFetch = async () => {
try {
// 1. Dispatch the action
const resultAction = await dispatch(fetchUser(id))
// 2. Unwrap the result to get the payload (or throw error)
const user = unwrapResult(resultAction)
console.log('Got user:', user)
} catch (error) {
console.error('Failed to fetch:', error)
}
}
return <button onClick={handleFetch}>Load User</button>
}API Reference
createSagaAction<Returned, ThunkArg>(typePrefix)
Creates a Redux Toolkit Async Thunk bridge.
- Returns: An enhanced thunk action creator.
- If no saga picks the action up within 30 seconds, the promise rejects with an error telling you which watcher registration is missing (no silent hangs).
takeEveryAsync(patternOrCreator, saga, ...args)
Spawns a saga on each action.
- Automatically resolves/rejects the promise associated with the action.
- Pass the action creator (
takeEveryAsync(fetchUser, saga)) for full type inference, or a classic pattern/string. - Calling
promise.abort()on the dispatched action cancels the running saga.
takeLatestAsync(patternOrCreator, saga, ...args)
Same as takeEveryAsync, but cancels previous running task on new actions.
- Propagates cancellation to the saga and rejects the promise with "Aborted".
takeAggregateAsync(patternOrCreator, saga, ...args)
Wait for the saga to finish. Identical actions (same meta.arg, compared structurally) dispatched while it's running share the same promise result; actions with different args run independently.
- Perfect for de-duplicating rapid "Refresh" calls.
putAsync(action)
Dispatches an action and waits for its Saga to finish.
const result = yield putAsync(otherAction())- Typed:
const result = yield* putAsync(otherAction())infers the result type.
SagaPendingAction<typeof actionCreator>
TypeScript helper: the pending action your worker saga receives (typed meta.arg included). SagaActionFromCreator is kept for backwards compatibility.
useSagaActions(actions)
React hook that binds actions to dispatch and automatically unwraps the returned promise.
- Stable: Uses shallow comparison on the input object to prevent infinite loops.
- Returns: An object with the same keys, where each thunk returns
Promise<Result>(unwrapped) that also exposes.abort()for cancellation; plain action creators are passed through unchanged.
License
ISC
