-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.html
executable file
·538 lines (504 loc) · 17 KB
/
index.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
<title>Real-life experiences with redux-saga</title>
<link rel="stylesheet" href="css/reveal.css">
<link rel="stylesheet" href="css/theme/moon.css">
<!-- Theme used for syntax highlighting of code -->
<link rel="stylesheet" href="lib/css/tomorrow-night.css">
<link rel="stylesheet" href="css/styles.css">
<!-- Printing and PDF exports -->
<script>
var link = document.createElement('link');
link.rel = 'stylesheet';
link.type = 'text/css';
link.href = window.location.search.match(/print-pdf/gi) ?
'css/print/pdf.css' : 'css/print/paper.css';
document.getElementsByTagName('head')[0].appendChild(link);
</script>
</head>
<body>
<div class="reveal">
<div class="slides">
<!-- START SLIDES -->
<section>
<h1>Real-life experiences with redux-saga</h1>
<p>ES6 generators, TypeScript 2.0, and more!</p>
<small>
Futurice WWWeeklies 26.8.2016<br />
by Ville Saarinen, <a href="https://twitter.com/vsaarinen">@vsaarinen</a>
</small>
</section>
<section data-background-color="#ffffff">
<h2 style="color: #444">My background</h2>
<div class="logos flex">
<img class="company" src="images/futurice.png" />
<img class="company" src="images/flowdock.png" />
<img class="company" src="images/sharetribe.png" />
<img class="company" src="images/lucify.png" />
</div>
</section>
<section data-background-color="#ffffff">
<div class="logos flex">
<a href="https://www.lucify.com">
<img class="company big" src="images/lucify.png" />
</a>
</div>
</section>
<section>
<h2>Minard</h2>
<p>
A preview server for static web projects
</p>
</section>
<section>
<h1><a href="http://www.lucify.com/minard/">Demo</a></h1>
</section>
<section>
<h2>Tech stack</h2>
<div class="flex">
<div>
<h3>Backend</h3>
<ul>
<li>TypeScript 2.0</li>
<li>Hapi</li>
<li>Docker</li>
<li>GitLab</li>
</ul>
</div>
<div>
<h3>Frontend</h3>
<ul>
<li>TypeScript 2.0</li>
<li>React</li>
<li>redux</li>
<li>redux-saga</li>
</ul>
</div>
</div>
</section>
<section>
<h2>Async operations in React</h2>
<ul>
<li class="fragment"><strong>Inline</strong></li>
<ul>
</section>
<section>
<pre><code class="ts" data-trim>
// component.tsx
const loadData = (dispatch: Dispatch<any>, id: string) => {
fetch(`/api/data/${id}`)
.then(response =>
response.ok ? response.json() : Promise.reject(response.error)
).then(json => {
dispatch({
type: 'STORE_DATA',
data: json
});
}).catch(error => {
dispatch({
type: 'DATA_FETCH_FAILED',
error: error || 'Something bad happened'
});
});
};
loadData(this.props.dispatch, this.props.id);
</code></pre>
<h3 class="fragment">Problems</h3>
<ul>
<li class="fragment">Duplicating async code</li>
<li class="fragment">Handling race conditions 😬</li>
</ul>
</section>
<section>
<h2>Async operations in React</h2>
<ul>
<li>Inline</li>
<li class="fragment"><strong>Centralized logic</strong></li>
<ul>
</section>
<section>
<pre><code class="ts" data-trim data-noescape>
// actions.ts
const storeData = (data: any) => ({ type: 'STORE_DATA', data });
const fetchFailed = (error: string) => ({ type: 'FETCH_FAILED', error });
let inProgressFetches: string[] = [];
export const loadData = (dispatch: Dispatch<any>, id: string) => {
if (inProgressFetches.indexOf(id) > -1) return;
inProgressFetches.push(id);
fetch(`/api/data/${id}`)
.then(response =>
response.ok ? response.json() : Promise.reject(response.error)
).then(json => {
dispatch(storeData(json));
inProgressFetches = inProgressFetches.filter(n => n !== id);
}).catch(error => {
dispatch(fetchFailed(error));
inProgressFetches = inProgressFetches.filter(n => n !== id);
});
};
// component.tsx
import { loadData } from './actions';
loadData(this.props.dispatch, this.props.id);
</code></pre>
</section>
<section>
<h2>Problems</h2>
<ul>
<li class="fragment">Passing dispatch around</li>
<li class="fragment">
Two different types of action creators:
<ul>
<li>Synchronous object creators</li>
<li>Asynchronous dispatchers</li>
</ul>
</li>
</ul>
</section>
<section>
<h2>Async operations in React</h2>
<ul>
<li>Inline</li>
<li>Centralized logic</li>
<li class="fragment"><strong>redux-thunk</strong></li>
<ul>
</section>
<section>
<pre><code class="ts" data-trim data-noescape>
// actions.ts
const storeData = (data: any) => ({ type: 'STORE_DATA', data });
const fetchFailed = (error: string) => ({ type: 'FETCH_FAILED', error });
let inProgressFetches: string[] = [];
export const loadData = (id: string) => (dispatch: Dispatch<any>) => {
if (inProgressFetches.indexOf(id) > -1) return;
inProgressFetches.push(id);
fetch(`/api/data/${id}`)
.then(response =>
response.ok ? response.json() : Promise.reject(response.error)
).then(json => {
dispatch(storeData(json));
inProgressFetches = inProgressFetches.filter(n => n !== id);
}).catch(error => {
dispatch(fetchFailed(error));
inProgressFetches = inProgressFetches.filter(n => n !== id);
});
};
// component.tsx
import { loadData } from './actions';
this.props.dispatch(loadData(this.props.id));
</code></pre>
</section>
<section>
<h2>Problems</h2>
<ul>
<li class="fragment">…no major ones</li>
<li class="fragment">
Implementing certain logic is difficult:
<ul>
<li>Retrying requests</li>
<li>Reauth with tokens</li>
<li>Cancelling requests</li>
</ul>
</li>
</ul>
</section>
<section>
<h2>Async operations in React</h2>
<ul>
<li>Inline</li>
<li>Centralized logic</li>
<li>redux-thunk</li>
<li class="fragment"><strong>redux-saga</strong></li>
<ul>
</section>
<section>
<h2>Refresher: ES6 generators</h2>
</section>
<section>
<pre><code data-trim class="javascript">
function *generator() {
let i = 1;
while (true) {
yield i++;
}
}
const iterator = generator();
</code></pre>
</section>
<section>
<pre><code data-trim class="javascript">
function *testingGenerators() {
console.log('inside: starting');
const firstYieldReturn = yield 1;
console.log('inside: firstYieldReturn', firstYieldReturn);
const secondYieldReturn = yield 2;
console.log('inside: secondYieldReturn', secondYieldReturn);
return 3;
}
const iterator2 = testingGenerators();
</code></pre>
</section>
<section>
<h2>Async operations in React</h2>
<ul>
<li>Inline</li>
<li>Centralized logic</li>
<li>redux-thunk</li>
<li><strong>redux-saga</strong></li>
<ul>
</section>
<section>
<h2>redux-saga</h2>
<p>
Sagas are like <em>long-running background processes</em>.<br />
The idea comes from the database field, from a paper published in 1987.
</p>
<p class="fragment">
redux-saga is a redux middleware that provides saga functionality using
ES6 generators.
</p>
<p class="fragment">
redux-saga allows you to intercept redux actions and do funky stuff using
<em>effects</em>.
</p>
</section>
<section data-transition="slide-in fade-out">
<h2>redux-saga effects</h2>
<p>
redux-saga effects are simply Javascript objects. They are yielded to
the redux-saga middleware to tell it what to do.
</p>
<p class="fragment">
The redux-saga library comes with built-in support for certain types
of effects, along with effect creators. Using these primitives, you can
do some really powerful stuff.
</p>
</section>
<section data-transition="fade-in slide-out">
<h2>redux-saga effects</h2>
<ul class="no-bullets">
<li>
<strong>take</strong>: Wait until the specified Redux action and return it.
</li>
<li class="fragment">
<strong>put</strong>: Pass the given action to the Redux store.
</li>
<li class="fragment">
<strong>select</strong>: Get a value out of the Redux state tree.
</li>
<li class="fragment">
<strong>call</strong>: Call the given function (blocking), returning its value.
</li>
<li class="fragment">
<strong>fork</strong>: Call the given function (non-blocking), returning a reference to it.
</li>
<li class="fragment">
<strong>join</strong>: Wait until the referenced forked function terminates.
</li>
<li class="fragment">
<strong>cancel</strong>: Cancel the referenced forked function.
</li>
<li class="fragment">
<strong>race</strong>: Return when one of the given functions returns, cancelling the rest.
</li>
</ul>
</section>
<section>
<h2>Setting it up</h2>
<pre><code data-trim class="ts">
// createStore.ts
import { applyMiddleware, createStore } from 'redux';
import saga from './sagas';
import reducer from './reducers';
const sagaMiddleware = createSagaMiddleware();
const store = createStore(reducer, {}, applyMiddleware(sagaMiddleware));
sagaMiddleware.run(saga);
</code></pre>
</section>
<section>
<h2>Triggering</h2>
<pre><code data-trim class="ts">
// sagas/index.ts
export default function* watchForLoadData(): IterableIterator<Effect> {
while (true) {
const { id } = yield take('LOAD_DATA');
yield fork(loadData, id);
}
}
function* loadData(id: string) : IterableIterator<Effect> {
const { response, error } = yield call(api.fetchData, id);
if (response) {
yield put({ type: 'STORE_DATA', id, data: response.data });
} else {
yield put({ type: 'FETCH_ERROR', id, error });
}
}
// component.tsx
dispatch({ type: 'LOAD_DATA', id });
</code></pre>
</section>
<section>
<h2>Recipes</h2>
<h3>Parallel tasks</h3>
<pre><code data-trim class="ts">
function *fetchUsers(userIds: string[]): IterableIterator<Effect[]> {
const users = yield userIds.map(id => call(fetchUser, id));
yield put({ type: 'STORE_USERS', users });
}
</code></pre>
</section>
<section>
<h2>Recipes</h2>
<h3>Timeouts</h3>
<pre><code data-trim class="ts">
const delay = (ms: number) => new Promise(res => setTimeout(res, ms));
function* fetchPostsWithTimeout(): IterableIterator<Effect> {
const { posts, timeout } = yield race({
posts: call(fetchPosts),
timeout: call(delay, 1000)
});
if (posts)
put({ type: 'POSTS_RECEIVED', posts });
else
put({ type: 'TIMEOUT_ERROR' });
}
</code></pre>
</section>
<section>
<h2>Recipes</h2>
<h3>Cancelling</h3>
<pre><code data-trim class="ts">
function* backgroundTask(): IterableIterator<Effect> {
while (true) { ... }
}
function* watchStartBackgroundTask(): IterableIterator<Effect> {
while (true) {
yield take('START_BACKGROUND_TASK');
yield race({
task: call(backgroundTask),
cancel: take('CANCEL_TASK')
});
}
}
</code></pre>
</section>
<section>
<h2>Recipes</h2>
<h3>Debouncing</h3>
<pre><code data-trim class="ts">
const delay = (ms: number) => new Promise(res => setTimeout(res, ms));
function* handleInput(input: string): IterableIterator<Effect> {
// debounce by 500ms
yield call(delay, 500);
...
}
function* watchInput() {
let task: Task;
while (true) {
const { input } = yield take('INPUT_CHANGED');
if (task) {
yield cancel(task);
}
task = yield fork(handleInput, input);
}
}
</code></pre>
</section>
<section>
<h2>Actual code</h2>
</section>
<section>
<h2>Question</h2>
<p>
Why does <code>call</code> exist?<br />
Why not just call the function or generator directly?
</p>
<h3 class="fragment">Testing becomes awesome!</h3>
</section>
<section>
<h2>Unit testing with redux-saga</h2>
<small class="fragment">aka. mocking is for suckers</small>
<p class="fragment">
All you're doing is building generators that produce effects,
i.e. plain JavaScript objects. No need to mock anything.
</p>
<p class="fragment">
Testing becomes functional, with no side-effects.
</p>
</section>
<section>
<h2>Actual tests</h2>
</section>
<section>
<h2>Downsides of redux-saga</h2>
<ul>
<li class="fragment">Not all browsers support generators</li>
<li class="fragment">Testing requires (some) knowledge of implementation</li>
<li class="fragment">Probably overkill for many use cases</li>
</ul>
</section>
<section>
<h2>Upsides of redux-saga</h2>
<ul>
<li class="fragment">
All logic with side-effects in one place. Allows you to focus on a
really declarative style with React.
</li>
<li class="fragment">Even though code is async, it's very easy to follow.</li>
<li class="fragment">Effects allow you to compose very powerful operations.</li>
<li class="fragment">Mocking not required for unit tests.</li>
</ul>
</section>
<section>
<h2>That's about it!</h2>
<p>
If we have time and any of you are interested, I'd be more than happy
to talk about: <strong>TypeScript 2.0</strong>, <strong>what to store
in the Redux state while loading in progress or errors</strong>, <strong>structuring
React applications</strong>...
</p>
</section>
<section>
<h2>Want to pilot Lucify's Minard?</h2>
<p>
If you're working on static web projects (i.e. projects with no
backend in the repo), come talk! We're launching our closed alpha
in November.
</p>
</section>
<section>
<h3>Acknowledgements</h3>
<ul>
<li><strong>Dan Abramov</strong> for redux and his <a href="http://stackoverflow.com/a/35415559">excellent online explanations</a>.</li>
<li><strong>Yassine Elouafi</strong> for redux-saga and the <a href="http://yelouafi.github.io/redux-saga/docs/advanced/index.html">great documentation</a>.</li>
</ul>
</section>
<!-- END SLIDES -->
</div>
</div>
<script src="lib/js/head.min.js"></script>
<script src="js/reveal.js"></script>
<script>
// More info https://github.com/hakimel/reveal.js#configuration
Reveal.initialize({
history: true,
controls: false,
transition: 'slide', // none/fade/slide/convex/concave/zoom
transitionSpeed: 'fast', // default/fast/slow
// More info https://github.com/hakimel/reveal.js#dependencies
dependencies: [
{ src: 'plugin/markdown/marked.js' },
{ src: 'plugin/markdown/markdown.js' },
{ src: 'plugin/notes/notes.js', async: true },
{
src: 'plugin/highlight/highlight.js',
async: true,
callback: function() { hljs.initHighlightingOnLoad(); }
}
]
});
</script>
</body>
</html>