agentleFS
anivaranivar/redux-saga-skill/AGENTS.md

redux-saga-skill

AGENTS.md2 starsChanged 3 months agoMITView on GitHub

This document is for AI agents and LLMs to follow when writing, reviewing, or debugging redux-saga code. It compiles all rules and references into a single executable guide. Baseline: redux-saga 1.5.1 with Redux Toolkit (configureStore) Redux-Saga is generator-based middleware for managing complex side effects in Redux applications. Use it for workflow orchestration — parallel tasks, cancellation, racing, channels, and long-running background processes. For data fetching, prefer RTK Query. For simple async, prefer createAsyncThunk. For reactive slice logic, prefer createListenerMiddleware. Every…

  • Where files are headingNew AGENTS.md files have more rules about keeping secrets out of the code, and fewer about code style.

    Of the AGENTS.md files we read, the 32,671 first seen in the last six months, against the older ones: the kind of rule that gained most share, and the kind that lost most. About files like this in general, not this one, and an estimate, since a kind is a pattern in the words.

  • In this repositoryOne other file it gives its agents.

The file

We split this AGENTS.md into the rules it gives an agent

4 rules. About 0 are common, 0 are distinctive, and 4 are very specific to this project.

  • ≈0

    Common · estimate

    Many files like this have a rule of this kind.

  • ≈0

    Distinctive · estimate

    This author's own choices. Worth a look.

  • 4

    Very specific

    Tied to their project's names, files or tools. Probably skip.

  • Common
  • Distinctive
  • Very specific
  1. Very specific:

    Every effect creator must be yielded.

    line 33
  2. Very specific:

    Never call async functions directly.

    line 51
  3. Very specific:

    Use expectSaga from redux-saga-test-plan.

    line 195
  4. Very specific:

    Use action creators from createSlice — no string duplication:

    line 397

≈ “Common” is an estimate: at least 1 in 5 of the 41,581 AGENTS.md files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.

Keep what fits and drop the rest. Your version, ready for your agents.
Files
AGENTS.md

Redux-Saga — Complete Guide

This document is for AI agents and LLMs to follow when writing, reviewing, or debugging redux-saga code. It compiles all rules and references into a single executable guide.

Baseline: redux-saga 1.5.1 with Redux Toolkit (configureStore)


Abstract

Redux-Saga is generator-based middleware for managing complex side effects in Redux applications. Use it for workflow orchestration — parallel tasks, cancellation, racing, channels, and long-running background processes. For data fetching, prefer RTK Query. For simple async, prefer createAsyncThunk. For reactive slice logic, prefer createListenerMiddleware.


Table of Contents

  1. Effects & Yielding — CRITICAL
  2. Fork Model & Concurrency — CRITICAL
  3. Testing — HIGH
  4. Error Handling — HIGH
  5. Channels & External I/O — MEDIUM
  6. Recipes & Patterns — MEDIUM
  7. RTK Integration — MEDIUM
  8. Troubleshooting — LOW

1. Effects & Yielding

Impact: CRITICAL

Rule: Always Yield Effects

Every effect creator must be yielded. Missing yield creates a synchronous infinite loop that freezes the app.

// INCORRECT — app freezes
while (true) {
  const action = take('REQUEST')
  call(fetchData, action.payload)
}

// CORRECT
while (true) {
  const action = yield take('REQUEST')
  yield call(fetchData, action.payload)
}

Rule: Use call() for Async Functions

Never call async functions directly. Use yield call() for testability, cancellation, and middleware control.

// INCORRECT — not testable, not cancellable
const user = yield api.fetchUser(id)

// CORRECT
const user = yield call(api.fetchUser, id)

call() returns a plain object describing the call — an instruction the middleware executes, not the call itself. Tests use deepEqual against the same effect creator instead of mocks.

Rule: Choose the Right Watcher

ScenarioWatcherWhy
Search / autocompletetakeLatestCancel stale requests
Form submission / paymenttakeLeadingPrevent duplicate processing
Notifications / loggingtakeEveryProcess every event
Sequential queueactionChannel + takeOne at a time, in order
Rate-limited UI eventsthrottleMax once per interval
Wait for typing to stopdebounceAfter silence period

Effect Creators Quick Reference

EffectBlockingPurpose
take(pattern)YesWait for matching action
takeMaybe(pattern)YesLike take, receives END
takeEvery(pattern, saga)NoConcurrent on every match
takeLatest(pattern, saga)NoCancel previous, run latest
takeLeading(pattern, saga)NoIgnore until current completes
put(action)NoDispatch action
putResolve(action)YesDispatch, wait for promise
call(fn, ...args)YesCall, wait for result
apply(ctx, fn, [args])YesCall with context
cps(fn, ...args)YesNode-style callback
fork(fn, ...args)NoAttached fork
spawn(fn, ...args)NoDetached fork
join(task)YesWait for task
cancel(task)NoCancel task
cancel()NoSelf-cancel
select(selector)NoQuery store state
actionChannel(pattern)NoBuffer actions
flush(channel)NoDrain buffered messages
cancelled()YesCheck cancellation in finally
delay(ms)YesPause execution
throttle(ms, pattern, saga)NoRate-limit
debounce(ms, pattern, saga)NoWait for silence
retry(n, delay, fn)YesRetry with backoff
race(effects)YesFirst wins
all([effects])If any child blocksParallel, wait all
setContext(props)NoUpdate context
getContext(prop)YesRead context

Pattern Matching

take, takeEvery, takeLatest, takeLeading, throttle, debounce accept:

  • '*' — all actions (only take/takeMaybe may omit the argument entirely)
  • 'ACTION_TYPE' — exact match
  • [type1, type2] — any in array
  • fn => boolean — custom predicate

For takeEvery, takeLatest, takeLeading, throttle, and debounce the pattern is a required parameter; use '*' for a catch-all watcher. Taking from a multicastChannel also requires a pattern: take(chan, '*'), not take(chan).


2. Fork Model & Concurrency

Impact: CRITICAL

Rule: Attached vs Detached Forks

fork (attached)spawn (detached)
Parent waits for childYesNo
Child error crashes parentYesNo
Parent cancel cancels childYesNo
Use whenChild is part of the workflowChild is independent
// Attached: analytics failure would crash checkout — BAD
yield fork(processPayment)
yield fork(trackAnalytics) // throws → processPayment cancelled

// Correct: analytics is independent
yield fork(processPayment)
yield spawn(trackAnalytics)

Rule: Fork Error Propagation

You cannot catch errors from fork() in a try/catch around the fork. Errors bubble to the call() site that invoked the parent.

// INCORRECT — catch never reached
try {
  yield fork(failingSaga)
} catch (e) { /* never reached */ }

// CORRECT — catch at the call site
function* root() {
  try {
    yield call(parentSaga) // errors from forks arrive here
  } catch (e) { ... }
}

Rule: Never Fork Inside Race

fork is non-blocking — it always wins the race immediately. Use call inside race.

// INCORRECT — fork always wins
yield race({ task: fork(work), timeout: delay(5000) })

// CORRECT
yield race({ result: call(work), timeout: delay(5000) })

Concurrency Patterns

actionChannel — Sequential Processing:

const chan = yield actionChannel('REQUEST')
while (true) {
  const action = yield take(chan)
  yield call(handleRequest, action)
}

Worker Pool — Limited Parallelism:

const chan = yield actionChannel('REQUEST')
for (let i = 0; i < 3; i++) yield fork(worker, chan)

3. Testing

Impact: HIGH

Rule: Prefer Integration Tests

Use expectSaga from redux-saga-test-plan. It doesn't couple tests to effect ordering.

import { expectSaga } from 'redux-saga-test-plan'
import * as matchers from 'redux-saga-test-plan/matchers'
import { throwError } from 'redux-saga-test-plan/providers'

it('fetches user', () => {
  return expectSaga(fetchUserSaga, action)
    .provide([[matchers.call.fn(api.fetchUser), user]])
    .put(fetchUserSuccess(user))
    .run()
})

it('handles error', () => {
  return expectSaga(fetchUserSaga, action)
    .provide([[matchers.call.fn(api.fetchUser), throwError(new Error('500'))]])
    .put(fetchUserFailure('500'))
    .run()
})

Rule: Use Providers for Mocking

Static providers with partial matchers are preferred:

.provide([
  [matchers.call.fn(api.fetchUser), mockUser],       // match function, any args
  [matchers.select.selector(getToken), 'mock-token'], // mock selector
  [matchers.call.fn(api.save), throwError(error)],    // simulate error
])

Rule: Test Sagas with Reducers

it('loads users into state', () => {
  return expectSaga(loadUsersSaga)
    .withReducer(usersReducer)
    .provide([[matchers.call.fn(api.fetchUsers), users]])
    .hasFinalState({ users, loading: false, error: null })
    .run()
})

Unit Testing (When Order Matters)

import { testSaga } from 'redux-saga-test-plan'

testSaga(checkoutSaga, action)
  .next()
  .put(showLoading())       // must be first
  .next()
  .call(api.processPayment) // must be second
  .next()
  .isDone()

Testing Without Libraries (runSaga)

async function recordSaga(saga, action, state = {}) {
  const dispatched = []
  await runSaga(
    { dispatch: (a) => dispatched.push(a), getState: () => state },
    saga, action,
  ).toPromise()
  return dispatched
}

Vitest / Jest

Both work identically. expectSaga.run() returns a Promise:

  • Jest: return expectSaga(saga).run()
  • Vitest: await expectSaga(saga).run()

4. Error Handling

Impact: HIGH

Rule: Cancellation Cleanup with finally

function* syncSaga() {
  try {
    while (true) {
      yield call(fetchData)
      yield delay(10000)
    }
  } finally {
    if (yield cancelled()) {
      yield put(syncCancelled())
    }
  }
}

Cancellation propagates downward through attached forks. Each cancelled generator jumps to its finally block.

Rule: Root Saga Error Boundaries

// INCORRECT — one crash kills all
yield all([watchAuth(), watchFetch(), watchAnalytics()])

// CORRECT — isolated error boundaries
function* safeSaga(saga) {
  yield spawn(function* () {
    try {
      yield call(saga)
    } catch (e) {
      console.error(`${saga.name} failed:`, e)
    }
  })
}

export default function* rootSaga() {
  yield safeSaga(watchAuth)
  yield safeSaga(watchFetch)
  yield safeSaga(watchAnalytics)
}

5. Channels & External I/O

Impact: MEDIUM

eventChannel — External Events

function createSocketChannel(socket) {
  return eventChannel((emit) => {
    // sanitize: never emit null/undefined; prefer `{ data }` over a bare primitive
    socket.on('message', (data) => { if (data != null) emit({ data }) })
    socket.on('close', () => emit(END))
    return () => socket.close()
  })
}

Two contract points the docs are explicit about. The subscriber must "sanitize your event sources as to not pass null or undefined through the event channel" — structure the data "like your redux actions. { number } over number." And messages on an eventChannel are not buffered by default: "if not provided, messages will not be buffered on this channel", so anything emitted while no taker is registered is lost. Pass a buffer when every message matters. channel() differs — it queues up to 10 by default — and actionChannel buffers without limit.

Buffer Types

BufferOn Overflow
buffers.none() (eventChannel default)Drops
buffers.fixed(n)Throws
buffers.expanding(n)Grows
buffers.dropping(n)Drops newest
buffers.sliding(n)Drops oldest

runSaga — Outside Redux

runSaga({ channel, dispatch, getState }, mySaga)

6. Recipes & Patterns

Impact: MEDIUM

  • Login flow: fork auth + take(['LOGOUT', 'LOGIN_ERROR']) + cancel
  • Polling: while(true) + call + delay in a forked task, cancel on STOP
  • Optimistic update: put(optimistic) + race({ undo: take('UNDO'), commit: delay(5000) }), started with spawn so cancellation can't strand the UI between revert and commit
  • Pagination: take('LOAD_MORE') in a loop, track page/hasMore
  • Batching outgoing side effects: actionChannel + flush on interval
  • Batching dispatched actions: wrap stdChannel().put to unwrap redux-batched-actions' BATCH envelope, then createSagaMiddleware({ channel }) — without it, watchers never see batched actions
  • Timeout wrapper: race({ result: call(saga), timeout: delay(ms) })
  • Parallel loading: yield all([call(a), call(b), call(c)])

See references/recipes.md for full code examples.


7. RTK Integration

Impact: MEDIUM

configureStore Setup

import createSagaMiddleware from 'redux-saga'
import { configureStore } from '@reduxjs/toolkit'

const sagaMiddleware = createSagaMiddleware()

const store = configureStore({
  reducer: rootReducer,
  middleware: (getDefault) => getDefault().concat(sagaMiddleware),
})

sagaMiddleware.run(rootSaga) // AFTER store creation

Sagas with RTK Slices

Use action creators from createSlice — no string duplication:

import { fetchUsers } from './usersSlice'

yield takeLatest(fetchUsers.type, fetchUsersSaga)
yield put(fetchUsersSuccess(users))

When to Use What

NeedTool
Data fetching + cachingRTK Query
Simple asynccreateAsyncThunk
Reactive slice logiccreateListenerMiddleware
Workflows, cancellation, channelsRedux-Saga

8. Troubleshooting

Impact: LOW

SymptomCauseFix
App freezesMissing yield in loopAdd yield before every effect
Missed actionsSaga blocked on callUse fork to stay responsive
Bad stack tracesAsync generatorsonError with sagaStack, babel-plugin-redux-saga
Saga doesn't startrun() before storeCall run() after configureStore
Undefined reaches a sagaEvent source emitted null/undefined into an eventChannelSanitize at the emit site; emit { data }, not a bare primitive
yield returns any (TS)TS can't infer generatorsType manually or use typed-redux-saga
Effect not executingMissing yield before effectyield put(action) not put(action)

Prerequisites

  • redux-saga ^1.5.1
  • @reduxjs/toolkit (recommended)
  • redux-saga-test-plan (for testing)
  • Node.js with ES2015 generator support (all modern runtimes)

License

MIT

Download now (ZIP)

Does it work?

Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.

No reviews yet

People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.

  • It worked
  • Partly
  • It didn't
What did you use it for? e.g. Reviewing pull requests in a Rails app

Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.

Your trail

Files you open will collect here, so you can find them again.

Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.

Now do this for your own.

Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.