0
# Utility Packages
1
2
Redux-Saga provides several utility packages that offer additional functionality for type checking, promises, symbols, and monitoring.
3
4
## Capabilities
5
6
### Type Checking Utilities (@redux-saga/is)
7
8
Utility functions for checking the type of values in Redux-Saga applications.
9
10
```typescript { .api }
11
/**
12
* Type checking utilities from @redux-saga/is
13
*/
14
// Basic type checks
15
function undef(value: any): value is undefined;
16
function notUndef(value: any): value is {};
17
function func(value: any): value is Function;
18
function number(value: any): value is number;
19
function string(value: any): value is string;
20
function array(value: any): value is any[];
21
function object(value: any): value is object;
22
23
// Redux-Saga specific type checks
24
function promise(value: any): value is Promise<any>;
25
function iterator(value: any): value is Iterator<any>;
26
function iterable(value: any): value is Iterable<any>;
27
function task(value: any): value is Task;
28
function sagaAction(value: any): boolean;
29
function observable(value: any): boolean;
30
function buffer(value: any): value is Buffer<any>;
31
function pattern(value: any): boolean;
32
function channel(value: any): value is Channel<any>;
33
function stringableFunc(value: any): boolean;
34
function symbol(value: any): value is symbol;
35
function multicast(value: any): value is MulticastChannel<any>;
36
function effect(value: any): value is Effect;
37
```
38
39
**Usage Examples:**
40
41
```typescript
42
import * as is from "@redux-saga/is";
43
44
function* validateInputs(action) {
45
if (!is.object(action.payload)) {
46
throw new Error('Payload must be an object');
47
}
48
49
if (is.promise(action.payload.data)) {
50
const data = yield action.payload.data;
51
// Handle promise data
52
}
53
54
if (is.channel(action.payload.source)) {
55
// Handle channel input
56
const message = yield take(action.payload.source);
57
}
58
}
59
```
60
61
### Symbol Constants (@redux-saga/symbols)
62
63
Provides access to all symbols used internally by Redux-Saga.
64
65
```typescript { .api }
66
/**
67
* Redux-Saga symbol constants
68
*/
69
const CANCEL: unique symbol;
70
const SAGA_ACTION: unique symbol;
71
const TASK: unique symbol;
72
const SAGA_LOCATION: unique symbol;
73
const CHANNEL_END_TYPE: unique symbol;
74
const IO: unique symbol;
75
const MATCH: unique symbol;
76
const MULTICAST: unique symbol;
77
const SELF_CANCELLATION: unique symbol;
78
const TASK_CANCEL: unique symbol;
79
const TERMINATE: unique symbol;
80
```
81
82
**Usage Examples:**
83
84
```typescript
85
import { CANCEL, SAGA_ACTION } from "@redux-saga/symbols";
86
87
function* cancellableSaga() {
88
try {
89
yield call(longRunningOperation);
90
} catch (error) {
91
if (error === CANCEL) {
92
console.log('Saga was cancelled');
93
// Cleanup logic
94
} else {
95
throw error;
96
}
97
}
98
}
99
100
function* detectSagaActions() {
101
const action = yield take();
102
if (action[SAGA_ACTION]) {
103
console.log('This action was dispatched by a saga');
104
}
105
}
106
```
107
108
### Deferred Promises (@redux-saga/deferred)
109
110
Utilities for creating deferred promises that can be resolved or rejected externally.
111
112
```typescript { .api }
113
/**
114
* Create a deferred promise
115
* @returns Deferred object with promise, resolve, and reject methods
116
*/
117
function deferred<T = any>(): Deferred<T>;
118
119
/**
120
* Create an array of deferred promises
121
* @param length - Number of deferred promises to create
122
* @returns Array of deferred objects
123
*/
124
function arrayOfDeferred<T = any>(length: number): Deferred<T>[];
125
126
interface Deferred<T> {
127
promise: Promise<T>;
128
resolve(value: T | Promise<T>): void;
129
reject(reason?: any): void;
130
}
131
```
132
133
**Usage Examples:**
134
135
```typescript
136
import deferred, { arrayOfDeferred } from "@redux-saga/deferred";
137
138
function* coordinatedSagas() {
139
// Create deferred for coordination
140
const coordination = deferred();
141
142
// Start multiple sagas
143
yield fork(taskA, coordination);
144
yield fork(taskB, coordination);
145
146
// Wait for coordination signal
147
yield coordination.promise;
148
console.log('All tasks coordinated');
149
}
150
151
function* batchProcessing() {
152
const batchSize = 5;
153
const batch = arrayOfDeferred(batchSize);
154
155
// Start batch processing
156
for (let i = 0; i < batchSize; i++) {
157
yield fork(processItem, i, batch[i]);
158
}
159
160
// Wait for all items to complete
161
yield all(batch.map(d => d.promise));
162
}
163
```
164
165
### Promise-based Delay (@redux-saga/delay-p)
166
167
Promise-based delay utility with cancellation support.
168
169
```typescript { .api }
170
/**
171
* Create a cancellable delay promise
172
* @param ms - Milliseconds to delay
173
* @param value - Optional value to resolve with
174
* @returns Cancellable promise that resolves after delay
175
*/
176
function delay<T = true>(ms: number, value?: T): Promise<T> & { cancel(): void };
177
```
178
179
**Usage Examples:**
180
181
```typescript
182
import delay from "@redux-saga/delay-p";
183
184
function* timeoutPatternSaga() {
185
try {
186
// Create cancellable delay
187
const delayPromise = delay(5000, 'timeout');
188
189
// Use with race for timeout pattern
190
const { response, timeout } = yield race({
191
response: call(api.fetchData),
192
timeout: delayPromise
193
});
194
195
if (timeout) {
196
console.log('Request timed out');
197
} else {
198
console.log('Request completed:', response);
199
// Cancel the delay to free resources
200
delayPromise.cancel();
201
}
202
} catch (error) {
203
console.error('Error in timeout pattern:', error);
204
}
205
}
206
```
207
208
### Saga Monitor (@redux-saga/simple-saga-monitor)
209
210
Basic saga monitor implementation for debugging and logging saga execution.
211
212
```typescript { .api }
213
/**
214
* Simple saga monitor for logging saga events
215
* @param options - Configuration options
216
* @returns SagaMonitor instance
217
*/
218
function createSagaMonitor(options?: {
219
level?: 'info' | 'warning' | 'error';
220
effectTrigger?: boolean;
221
effectResolve?: boolean;
222
effectReject?: boolean;
223
effectCancel?: boolean;
224
actionDispatch?: boolean;
225
}): SagaMonitor;
226
227
/**
228
* Utility function for logging sagas
229
* @param effect - Effect to log
230
* @param effectId - Unique effect ID
231
* @param parentEffectId - Parent effect ID
232
*/
233
function logSaga(effect: Effect, effectId: number, parentEffectId?: number): void;
234
```
235
236
**Usage Examples:**
237
238
```typescript
239
import createSagaMiddleware from "redux-saga";
240
import createSagaMonitor from "@redux-saga/simple-saga-monitor";
241
242
// Create monitor with custom options
243
const sagaMonitor = createSagaMonitor({
244
level: 'info',
245
effectTrigger: true,
246
effectResolve: true,
247
effectReject: true,
248
actionDispatch: true
249
});
250
251
// Use monitor with saga middleware
252
const sagaMiddleware = createSagaMiddleware({
253
sagaMonitor
254
});
255
256
// Monitor will log all saga effects and actions to console
257
```
258
259
## Types
260
261
### Utility Type Definitions
262
263
```typescript { .api }
264
// Deferred types
265
interface Deferred<T> {
266
promise: Promise<T>;
267
resolve(value: T): void;
268
reject(reason?: any): void;
269
}
270
271
// Monitor types
272
interface SagaMonitor {
273
rootSagaStarted?(options: { effectId: number; saga: Saga; args: any[] }): void;
274
effectTriggered?(options: { effectId: number; parentEffectId: number; label: string; effect: Effect }): void;
275
effectResolved?(options: { effectId: number; result: any }): void;
276
effectRejected?(options: { effectId: number; error: any }): void;
277
effectCancelled?(options: { effectId: number }): void;
278
actionDispatched?(action: AnyAction): void;
279
}
280
281
// Type checking function types
282
type TypeChecker<T> = (value: any) => value is T;
283
type BooleanChecker = (value: any) => boolean;
284
```