agentleFS
intent-hqintent-hq/cloudlands-fe/.agents/skills/redux-saga/SKILL.md

redux-saga

Skill9 starsChanged 3 days agoApache-2.0View on GitHub

Generic redux-saga API reference for agents. Covers createSagaMiddleware, middleware.run, runSaga, Effect creators, effect combinators, watcher helpers, channel support, buffers, Task/Channel/Buffer/SagaMonitor interfaces, cancellation, context, blocking vs non-blocking semantics, and testing helpers.

1 other project uses a version of this.

Adopted by

Most recently taken up by

  • Other versions1 project uses a version of this.

    Word for word · 0

    None found.

    Edited · 0

    None found.

    Wrote their own version · 1

    1. anivar/redux-saga-skill★ 2same name

    How matches are found. Word for word: the exact same text. Edited: shares passages with this file (“99% same” means 99% of its five-word phrases also appear here; 10% or more counts). Their own version: similar meaning, or, weakest, the same name. We can’t tell which project had it first. Projects are counted among the 200 most-starred candidates, and mentions are links to the repository we found, up to 50 per site, so both counts are a floor.

  • In this repository4 other files it gives its agents.

The file

We split this skill into the rules it gives an agent

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

  • ≈0

    Common · estimate

    Many files like this have a rule of this kind.

  • ≈4

    Distinctive · estimate

    This author's own choices. Worth a look.

  • 6

    Very specific

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

  • Common
  • Distinctive
  • Very specific
  1. Distinctive:

    Use this skill for generic redux-saga API behavior.

    line 26
  2. Distinctive:

    Before editing code or docs that use this skill:

    line 30
  3. Very specific:

    MUST: verify watcher ownership before adding takeEvery, takeLatest,takeLeading, throttle, or debounce for an existing trigger.

    line 34
  4. Distinctive:

    SHOULD: prefer native redux-saga channel-aware effects before adding wrapperutilities.

    line 35
  5. Very specific:

    Use take(pattern) for one action, takeMaybe(pattern) when the saga must receivethe END sentinel instead of auto-terminating, and watcher …

    line 77
  6. Very specific:

    Use cancel(task), cancel([...tasks]), or cancel() for self-cancellation.Cancellation calls the generator's return(), jumps to finally, and …

    line 122
  7. Very specific:

    Use put(action) for scheduled dispatch, putResolve(action) when dispatch returnsa Promise and the saga must wait, put(channel, message) for …

    line 126
  8. Very specific:

    Use actionChannel(pattern, buffer?) to queue matching store actions while a workeris blocked.

    line 156
  9. Very specific:

    Use race when the first completion wins.

    line 190
  10. Distinctive:

    Prefer effect-level assertions for small generators and integration-style sagatests for cancellation, channel cleanup, and watcher …

    line 261

≈ “Common” is an estimate: at least 1 in 5 of the 364,980 skill 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
SKILL.md

redux-saga — API reference skill

Source: official redux-saga API Reference, https://redux-saga.js.org/docs/api, retrieved 2026-05-15.

Use this skill for generic redux-saga API behavior.

Agent Preflight Compliance Contract

Before editing code or docs that use this skill:

  • MUST identify whether the target code uses plain redux-saga or this repo'styped-redux-saga conventions; adapt examples accordingly.
  • MUST cite this skill and any package-specific saga skill used in the handoff.
  • MUST verify watcher ownership before adding takeEvery, takeLatest,takeLeading, throttle, or debounce for an existing trigger.
  • SHOULD prefer native redux-saga channel-aware effects before adding wrapperutilities.
  • NEVER introduce runtime source, dependency, or artifact routing changes whenonly API guidance is requested.

Setup — middleware and root saga startup

createSagaMiddleware(options) creates Redux middleware. Supported options includeinitial context, sagaMonitor, onError, effectMiddlewares, and a customchannel used by take and put effects.

import { applyMiddleware, createStore } from 'redux';
import createSagaMiddleware from 'redux-saga';
import { all, call } from 'redux-saga/effects';

function reducer(state = { ready: false }, action: { type: string }) {
  return action.type === 'READY' ? { ready: true } : state;
}

function* rootSaga() {
  yield all([call(backgroundSync)]);
}

const sagaMiddleware = createSagaMiddleware({
  onError(error, { sagaStack }) {
    console.error('uncaught saga error', error, sagaStack);
  },
});

const store = createStore(reducer, applyMiddleware(sagaMiddleware));
const task = sagaMiddleware.run(rootSaga);

function* backgroundSync() {
  yield call(Promise.resolve, undefined);
}

void task.toPromise();

middleware.run(saga, ...args) must be called after the saga middleware is mountedon the store. It returns a Task descriptor and drives yielded plain Effectobjects until the generator returns, throws, or is cancelled.

Core patterns

1. Waiting and watcher helpers

Use take(pattern) for one action, takeMaybe(pattern) when the saga must receivethe END sentinel instead of auto-terminating, and watcher helpers for commonloops. Patterns can be "*", strings, arrays, predicates, or action creators whosetoString() returns an action type.

import { call, fork, put, take, takeEvery, takeLatest, takeLeading } from 'redux-saga/effects';

function* loadUser(action: { type: string; userId: string }) {
  const user: User = yield call(api.loadUser, action.userId);
  yield put({ type: 'USER_LOADED', user });
}

export function* usersSaga() {
  yield takeEvery('USER_REQUESTED', loadUser); // concurrent workers
  yield takeLatest('SEARCH_CHANGED', runSearch); // cancel stale worker
  yield takeLeading('SUBMIT_ORDER', submitOrder); // ignore while running

  const action: { type: string } = yield take(['LOGOUT', 'SESSION_EXPIRED']);
  yield fork(cleanupSession, action);
}

takeEvery, takeLatest, takeLeading, throttle, and debounce also accept aChannel in place of a pattern. This is native redux-saga behavior; do not createwrapper utilities unless they add cleanup, typing, or domain value beyond the API.

2. Blocking and non-blocking effects

call, apply, and cps are blocking; fork and spawn start work withoutblocking the parent. fork is attached to the parent: parent completion waits forchildren, child errors bubble upward, and cancellation propagates downward. spawnis detached and does not share parent completion, error, or cancellation flow.

import { call, cancel, cancelled, fork, join, spawn } from 'redux-saga/effects';

function* worker() {
  try {
    yield call(api.sync);
  } finally {
    if (yield cancelled()) yield call(api.abortSync);
  }
}

function* supervisor() {
  const attachedTask: Task = yield fork(worker);
  const detachedTask: Task = yield spawn(backgroundMetrics);
  yield cancel(detachedTask); // non-blocking cancellation request
  yield join(attachedTask); // blocking wait for attachedTask outcome
}

Use cancel(task), cancel([...tasks]), or cancel() for self-cancellation.Cancellation calls the generator's return(), jumps to finally, and cancels thecurrently blocked effect plus attached child tasks.

3. Store I/O, state reads, context, and timing

Use put(action) for scheduled dispatch, putResolve(action) when dispatch returnsa Promise and the saga must wait, put(channel, message) for channel output, andselect(selector, ...args) for state reads. setContext(props) merges saga context;getContext(prop) reads one context value. delay(ms, value) blocks for time.

import {
  call,
  delay,
  getContext,
  put,
  putResolve,
  retry,
  select,
  setContext,
} from 'redux-saga/effects';

function* saveProfile(action: { type: string; id: string }) {
  const token: string = yield select((state: RootState) => state.session.token);
  yield setContext({ requestId: action.id });
  const requestId: string = yield getContext('requestId');

  const profile: Profile = yield retry(3, 1_000, api.loadProfile, token, requestId);
  yield put({ type: 'PROFILE_LOADED', profile });
  yield delay(250);
  yield putResolve({ type: 'PROFILE_PERSISTED' });
}

retry(maxTries, delayMs, fn, ...args) is a blocking helper built from call anddelay: it retries failures until success or attempts are exhausted, then rethrowsthe last error.

4. Channels, buffers, and cleanup

Use actionChannel(pattern, buffer?) to queue matching store actions while a workeris blocked. Use channel(buffer?) for task-to-task messages and eventChannel tobridge external event sources; the subscribe function must return an unsubscribefunction. Close channels in finally, and use flush(channel) to recover bufferedmessages during cleanup.

import { buffers, channel, eventChannel, END } from 'redux-saga';
import { actionChannel, call, flush, put, take } from 'redux-saga/effects';

function socketChannel(socket: WebSocket) {
  return eventChannel<string>((emit) => {
    socket.onmessage = (event) => emit(String(event.data));
    socket.onerror = () => emit(END);
    return () => socket.close();
  }, buffers.sliding(10));
}

function* serializeRequests() {
  const requests: Channel<RequestAction> = yield actionChannel('REQUEST', buffers.expanding(10));
  try {
    while (true) {
      const action: RequestAction = yield take(requests);
      yield call(api.sendRequest, action.payload);
    }
  } finally {
    const leftovers: RequestAction[] = yield flush(requests);
    yield put({ type: 'REQUESTS_FLUSHED', leftovers });
  }
}

const mailbox = channel<string>(buffers.fixed(5));

Buffer choices: buffers.none(), fixed(limit), expanding(initialSize),dropping(limit), and sliding(limit). The default channel() buffer queues upto 10 messages FIFO.

5. Concurrency combinators and helpers

Use race when the first completion wins; losing effects are automaticallycancelled. Use all to run effects in parallel and wait for all successes, or throwwhen any effect rejects.

import { all, call, debounce, delay, put, race, take, throttle } from 'redux-saga/effects';

function* fetchWithTimeout() {
  const { response, timeout } = yield race({
    response: call(api.fetchReport),
    timeout: delay(5_000),
  });
  if (timeout) yield put({ type: 'REPORT_TIMEOUT' });
  else yield put({ type: 'REPORT_READY', response });
}

function* rootSaga() {
  yield all([call(fetchWithTimeout), call(watchUpload)]);
  yield throttle(1_000, 'TYPEAHEAD_CHANGED', fetchSuggestions);
  yield debounce(300, 'FILTER_CHANGED', refreshResults);
  yield take('SHUTDOWN');
}

throttle(ms, patternOrChannel, saga, ...args) uses a sliding buffer of one recentmessage while suppressing new starts during the window. debounce(ms, patternOrChannel, saga, ...args) waits until messages settle before forking theworker.

Interface quick reference

InterfaceWhat agents need to know
TaskReturned by fork, spawn, middleware.run, and runSaga; supports isRunning(), isCancelled(), result(), error(), toPromise(), and cancel().
ChannelMessage queue with take(callback), put(message), flush(callback), and close(); closed empty channels deliver END.
BufferStrategy behind a channel; implements isEmpty(), put(message), and take().
SagaMonitorReceives rootSagaStarted, effectTriggered, effectResolved, effectRejected, effectCancelled, and actionDispatched events for instrumentation.

Blocking / non-blocking cheat sheet

EffectBlocking?Notes
take, takeMaybe, call, apply, cps, join, putResolve, cancelled, delay, retry, raceYesrace blocks until one branch wins, then cancels losers.
put, fork, spawn, cancel, actionChannel, flush, select, setContext, getContextNoselect resolves immediately against current state.
put(channel, message)DependsIt can block when an unbuffered put is consumed immediately by a taker.
all([...]) / all({ ... })MixedBlocks until all child effects complete; child effect types determine actual waits.
takeEvery, takeLatest, takeLeading, throttle, debounceNoHelpers fork watcher tasks; their internals may use blocking effects.

External execution with runSaga

runSaga(options, saga, ...args) starts a saga without Redux middleware. Provide achannel for take, a dispatch(output) function for put, and getState() forselect. It returns the same Task interface as middleware.run.

import { runSaga, stdChannel } from 'redux-saga';
import { put, take } from 'redux-saga/effects';

function* auditSaga() {
  const action: { type: string } = yield take('AUDIT');
  yield put({ type: 'AUDITED', action });
}

const dispatched: Array<{ type: string; action?: { type: string } }> = [];
const input = stdChannel();
const task = runSaga(
  { channel: input, dispatch: (output) => dispatched.push(output), getState: () => ({}) },
  auditSaga,
);

input.put({ type: 'AUDIT' });
await task.toPromise();

Testing helpers

  • cloneableGenerator(generatorFunc) from @redux-saga/testing-utils createscloneable generator instances for branch testing without replaying setup yields.
  • createMockTask() from @redux-saga/testing-utils returns a mock Task fortesting fork, join, and cancel flows.
  • Prefer effect-level assertions for small generators and integration-style sagatests for cancellation, channel cleanup, and watcher concurrency.
import { cloneableGenerator, createMockTask } from '@redux-saga/testing-utils';
import { cancel, fork } from 'redux-saga/effects';

function* worker() {}
function* parent() {
  const task: Task = yield fork(worker);
  yield cancel(task);
}

const generator = cloneableGenerator(parent)();
expect(generator.next().value).toEqual(fork(worker));
const mockTask = createMockTask();
expect(generator.next(mockTask).value).toEqual(cancel(mockTask));

Common mistakes

❌ Calling middleware.run before mounting middleware

middleware.run is only valid after the saga middleware is connected to the Reduxstore. Mount middleware first, then run the root saga. Source: redux-saga APIReference → middleware.run(saga, ...args). Priority: HIGH.

❌ Assuming take and takeMaybe handle END the same way

take(pattern) and take(channel) auto-terminate when they receive END from thestdChannel or a closed channel. takeMaybe returns the END object so the saga canhandle the closed-input case itself. Source: redux-saga API Reference → take /takeMaybe. Priority: MEDIUM.

❌ Forking when parent failure/cancellation should not affect the child

fork creates an attached task; errors bubble to the parent and cancellationpropagates through attached children. Use spawn only when detached top-levelbehavior is intentional. Source: redux-saga API Reference → fork / spawn.Priority: HIGH.

❌ Forgetting channel unsubscribe / close cleanup

eventChannel subscribe functions must return an unsubscribe callback, and sagaconsumers should close channels in finally when they own the channel lifecycle.Source: redux-saga API Reference → eventChannel / Channel. Priority: HIGH.

❌ Recreating native channel helpers as wrappers without added value

takeEvery, takeLatest, takeLeading, throttle, and debounce already acceptchannels. Add wrappers only for documented cleanup, typing, or domain-specificbehavior. Source: redux-saga API Reference → channel overloads for watcher helpers.Priority: MEDIUM.

See also

  • Official redux-saga API Reference: https://redux-saga.js.org/docs/api
  • Themis core store guidance: .agents/skills/themis/core/SKILL.md
  • Themis Svelte integration guidance: .agents/skills/themis/svelte/SKILL.md
  • Themis setup guidance: .agents/skills/themis/setup/SKILL.md

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.