SlideShare a Scribd company logo
Async flow control
with Redux Sagas
Pedro Solá @ 8fit
Sagas
- Write & reason about asynchronous code 

as if it was synchronous code
- Test like a boss
- Complex composition. (fork, cancel, join,
race, throttling)
Side effect
management
Action Middleware Reducers
• redux-thunk
• redux-sagas
State
- Generators
- Declarative effects
Sagas
The mental model is that a saga is like a separate thread in your
application that's solely responsible for side effects.
This thread can be started, paused and cancelled from the main
application with normal redux actions.
Generators
Specified by the function* declaration
Generators can suspend themselves
A generator will be suspended on the
yield keyword, returning control to the
callee.
Declarative Effects
You can view Effects like instructions to the middleware
to perform some operation (invoke some asynchronous
function, dispatch an action to the store).
{ '@@redux-saga/IO': true,
CALL: { context: null, fn: [Function], args: [ 1, 2, 3 ] } }
Timer app
example from: https://jaysoo.ca/2016/01/03/managing-processes-in-redux-using-sagas/
State machineInterface
No middleware
class Timer extends Component {
componentWillReceiveProps(nextProps) {
const { state: { status: currStatus } } = this.props;
const { state: { status: nextStatus } } = nextProps;
if (currState === 'Stopped' && nextState === 'Running') {
this._startTimer();
} else if (currState === 'Running' && nextState === 'Stopped') {
this._stopTimer();
}
}
_startTimer() {
this._intervalId = setInterval(() => {
this.props.tick();
}, 1000);
}
_stopTimer() {
clearInterval(this._intervalId);
}
// ...
}
Thunk
export default {
start: () => (
(dispatch, getState) => {
// This transitions state to Running
dispatch({ type: 'START' });
// Check every 1 second if we are still Running.
// If so, then dispatch a `TICK`, otherwise stop
// the timer.
const intervalId = setInterval(() => {
const { status } = getState();
if (status === 'Running') {
dispatch({ type: 'TICK' });
} else {
clearInterval(intervalId);
}
}, 1000);
}
)
// ...
};
Saga
function* runTimer() {
// The sagasMiddleware will start running this generator.
// Wake up when user starts timer.
while(yield take('START')) {
while(true) {
const { stop, timer } = yield race({
stop: take('STOP'),
timer: call(delay, ONE_SECOND),
});
// if the stop action has been triggered first,
// break out of the timer loop
if (stop) {
break;
} else {
yield put(actions.tick());
}
}
}
}
Testing
it('should cancel the timer after a STOP action', => {
const generator = runTimer(); // create the generator object
let next = generator.next(); // step into
// the generator is now suspended, waiting for a START
expect(next).toEqual(take('START'));
next = generator.next({ type: 'START' });
const timerRace = race({
stop: take('STOP'),
timer: call(delay, ONE_SECOND),
});
expect(next).toEqual(timerRace);
// let's trigger stop before the timer completes
next = generator.next({ type: 'STOP' });
// we expect the runTimer to be awaiting a START action now
expect(next).toEqual(take('START'));
});
Common uses
- API calls
- Data sync
- Business logic services
- Orchestration of components across
multiple screens in your applications
Summary
IMO despite being initially intimidating,
expressing asynchronous logic in sagas
feels very natural, and is very powerful.
pedro@8fit.com
pssssssst! upgrade your life! come work with these beautiful people
Thanks for listening ❤

More Related Content

PDF
Using React, Redux and Saga with Lottoland APIs
PDF
Async JavaScript Unit Testing
PDF
Workshop 20: ReactJS Part II Flux Pattern & Redux
PDF
Workshop 19: ReactJS Introduction
PDF
Workshop 22: React-Redux Middleware
PDF
Angular2 & ngrx/store: Game of States
PDF
Workshop 13: AngularJS Parte II
Using React, Redux and Saga with Lottoland APIs
Async JavaScript Unit Testing
Workshop 20: ReactJS Part II Flux Pattern & Redux
Workshop 19: ReactJS Introduction
Workshop 22: React-Redux Middleware
Angular2 & ngrx/store: Game of States
Workshop 13: AngularJS Parte II

What's hot (20)

PDF
React + Redux. Best practices
PDF
Workshop 14: AngularJS Parte III
PDF
Intro to Redux | DreamLab Academy #3
PDF
React & Redux
PDF
Workshop 17: EmberJS parte II
PDF
Workshop 23: ReactJS, React & Redux testing
PPTX
Better React state management with Redux
PDF
Quick start with React | DreamLab Academy #2
PDF
Building React Applications with Redux
PDF
Evan Schultz - Angular Camp - ng2-redux
PPTX
ProvJS: Six Months of ReactJS and Redux
PDF
Let's Redux!
PPTX
React hooks
PDF
React lecture
PDF
Redux with angular 2 - workshop 2016
PPTX
Redux training
PDF
React redux
PDF
React, Redux, ES2015 by Max Petruck
PDF
Introduction to Redux
PDF
React state managmenet with Redux
React + Redux. Best practices
Workshop 14: AngularJS Parte III
Intro to Redux | DreamLab Academy #3
React & Redux
Workshop 17: EmberJS parte II
Workshop 23: ReactJS, React & Redux testing
Better React state management with Redux
Quick start with React | DreamLab Academy #2
Building React Applications with Redux
Evan Schultz - Angular Camp - ng2-redux
ProvJS: Six Months of ReactJS and Redux
Let's Redux!
React hooks
React lecture
Redux with angular 2 - workshop 2016
Redux training
React redux
React, Redux, ES2015 by Max Petruck
Introduction to Redux
React state managmenet with Redux
Ad

Viewers also liked (19)

PPTX
The redux saga begins
PPTX
7 Redux challenges
ODP
Flossuk17 introduction to ovirt
DOCX
Carta de MORENA al comisionado de la ONU para los Derechos Humanos
PDF
Everything You Wanted to Know About LinkedIn, but Were Too Embarrassed to Ask
PPTX
Smart Attribution + Cross Device - #SMXMunich 2017 - www.cubed.ai
PDF
Applying Machine Learning to Live Patient Data
PDF
ENDOCA presentazione azienda e prodotti
PDF
10 Things You Didn’t Know About Mobile Email from Litmus & HubSpot
PDF
How to Earn the Attention of Today's Buyer
PDF
Modern Prospecting Techniques for Connecting with Prospects (from Sales Hacke...
PDF
Class 1: Email Marketing Certification course: Email Marketing and Your Business
PDF
Behind the Scenes: Launching HubSpot Tokyo
PDF
HubSpot Diversity Data 2016
PDF
Why People Block Ads (And What It Means for Marketers and Advertisers) [New R...
PDF
What is Inbound Recruiting?
PDF
3 Proven Sales Email Templates Used by Successful Companies
PDF
Add the Women Back: Wikipedia Edit-a-Thon
PDF
Design in Tech Report 2017
The redux saga begins
7 Redux challenges
Flossuk17 introduction to ovirt
Carta de MORENA al comisionado de la ONU para los Derechos Humanos
Everything You Wanted to Know About LinkedIn, but Were Too Embarrassed to Ask
Smart Attribution + Cross Device - #SMXMunich 2017 - www.cubed.ai
Applying Machine Learning to Live Patient Data
ENDOCA presentazione azienda e prodotti
10 Things You Didn’t Know About Mobile Email from Litmus & HubSpot
How to Earn the Attention of Today's Buyer
Modern Prospecting Techniques for Connecting with Prospects (from Sales Hacke...
Class 1: Email Marketing Certification course: Email Marketing and Your Business
Behind the Scenes: Launching HubSpot Tokyo
HubSpot Diversity Data 2016
Why People Block Ads (And What It Means for Marketers and Advertisers) [New R...
What is Inbound Recruiting?
3 Proven Sales Email Templates Used by Successful Companies
Add the Women Back: Wikipedia Edit-a-Thon
Design in Tech Report 2017
Ad

Similar to Asyc flow control with javascript generators - redux-saga (20)

PPTX
Using Redux-Saga for Handling Side Effects
PDF
Advanced patterns in asynchronous programming
PDF
Side effects-con-redux
PPTX
AngularJS, More Than Directives !
PDF
The Ring programming language version 1.9 book - Part 93 of 210
PDF
Productionizing spark
PDF
The Ring programming language version 1.8 book - Part 89 of 202
PDF
Ngrx slides
PDF
"Angular.js Concepts in Depth" by Aleksandar Simović
PDF
Sagas Middleware Architecture
PDF
The Ring programming language version 1.10 book - Part 95 of 212
PDF
Osol Pgsql
PDF
JavaScript Refactoring
PDF
Android Loaders : Reloaded
PDF
Operating Systems 3rd Edition Nutt Solutions Manual
PPT
Module04
PPTX
Timer Interceptor in Mule part 2
DOCX
Twin wheeler modified for arduino simplified serial protocol to sabertooth v22
PDF
Android Best Practices
PPT
Effective Spring Transaction Management
Using Redux-Saga for Handling Side Effects
Advanced patterns in asynchronous programming
Side effects-con-redux
AngularJS, More Than Directives !
The Ring programming language version 1.9 book - Part 93 of 210
Productionizing spark
The Ring programming language version 1.8 book - Part 89 of 202
Ngrx slides
"Angular.js Concepts in Depth" by Aleksandar Simović
Sagas Middleware Architecture
The Ring programming language version 1.10 book - Part 95 of 212
Osol Pgsql
JavaScript Refactoring
Android Loaders : Reloaded
Operating Systems 3rd Edition Nutt Solutions Manual
Module04
Timer Interceptor in Mule part 2
Twin wheeler modified for arduino simplified serial protocol to sabertooth v22
Android Best Practices
Effective Spring Transaction Management

Recently uploaded (20)

PPTX
MYSQL Presentation for SQL database connectivity
PDF
NewMind AI Weekly Chronicles - August'25-Week II
PDF
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
PDF
Spectral efficient network and resource selection model in 5G networks
PDF
Diabetes mellitus diagnosis method based random forest with bat algorithm
PPTX
sap open course for s4hana steps from ECC to s4
PDF
gpt5_lecture_notes_comprehensive_20250812015547.pdf
PDF
Unlocking AI with Model Context Protocol (MCP)
PPTX
Spectroscopy.pptx food analysis technology
PDF
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
PDF
Dropbox Q2 2025 Financial Results & Investor Presentation
PDF
cuic standard and advanced reporting.pdf
PDF
Reach Out and Touch Someone: Haptics and Empathic Computing
DOCX
The AUB Centre for AI in Media Proposal.docx
PDF
Empathic Computing: Creating Shared Understanding
PDF
Encapsulation theory and applications.pdf
PPTX
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
PPTX
Machine Learning_overview_presentation.pptx
PDF
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
PDF
Chapter 3 Spatial Domain Image Processing.pdf
MYSQL Presentation for SQL database connectivity
NewMind AI Weekly Chronicles - August'25-Week II
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
Spectral efficient network and resource selection model in 5G networks
Diabetes mellitus diagnosis method based random forest with bat algorithm
sap open course for s4hana steps from ECC to s4
gpt5_lecture_notes_comprehensive_20250812015547.pdf
Unlocking AI with Model Context Protocol (MCP)
Spectroscopy.pptx food analysis technology
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
Dropbox Q2 2025 Financial Results & Investor Presentation
cuic standard and advanced reporting.pdf
Reach Out and Touch Someone: Haptics and Empathic Computing
The AUB Centre for AI in Media Proposal.docx
Empathic Computing: Creating Shared Understanding
Encapsulation theory and applications.pdf
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
Machine Learning_overview_presentation.pptx
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
Chapter 3 Spatial Domain Image Processing.pdf

Asyc flow control with javascript generators - redux-saga

  • 1. Async flow control with Redux Sagas Pedro Solá @ 8fit
  • 2. Sagas - Write & reason about asynchronous code 
 as if it was synchronous code - Test like a boss - Complex composition. (fork, cancel, join, race, throttling)
  • 3. Side effect management Action Middleware Reducers • redux-thunk • redux-sagas State
  • 4. - Generators - Declarative effects Sagas The mental model is that a saga is like a separate thread in your application that's solely responsible for side effects. This thread can be started, paused and cancelled from the main application with normal redux actions.
  • 5. Generators Specified by the function* declaration Generators can suspend themselves A generator will be suspended on the yield keyword, returning control to the callee.
  • 6. Declarative Effects You can view Effects like instructions to the middleware to perform some operation (invoke some asynchronous function, dispatch an action to the store). { '@@redux-saga/IO': true, CALL: { context: null, fn: [Function], args: [ 1, 2, 3 ] } }
  • 7. Timer app example from: https://jaysoo.ca/2016/01/03/managing-processes-in-redux-using-sagas/ State machineInterface
  • 8. No middleware class Timer extends Component { componentWillReceiveProps(nextProps) { const { state: { status: currStatus } } = this.props; const { state: { status: nextStatus } } = nextProps; if (currState === 'Stopped' && nextState === 'Running') { this._startTimer(); } else if (currState === 'Running' && nextState === 'Stopped') { this._stopTimer(); } } _startTimer() { this._intervalId = setInterval(() => { this.props.tick(); }, 1000); } _stopTimer() { clearInterval(this._intervalId); } // ... }
  • 9. Thunk export default { start: () => ( (dispatch, getState) => { // This transitions state to Running dispatch({ type: 'START' }); // Check every 1 second if we are still Running. // If so, then dispatch a `TICK`, otherwise stop // the timer. const intervalId = setInterval(() => { const { status } = getState(); if (status === 'Running') { dispatch({ type: 'TICK' }); } else { clearInterval(intervalId); } }, 1000); } ) // ... };
  • 10. Saga function* runTimer() { // The sagasMiddleware will start running this generator. // Wake up when user starts timer. while(yield take('START')) { while(true) { const { stop, timer } = yield race({ stop: take('STOP'), timer: call(delay, ONE_SECOND), }); // if the stop action has been triggered first, // break out of the timer loop if (stop) { break; } else { yield put(actions.tick()); } } } }
  • 11. Testing it('should cancel the timer after a STOP action', => { const generator = runTimer(); // create the generator object let next = generator.next(); // step into // the generator is now suspended, waiting for a START expect(next).toEqual(take('START')); next = generator.next({ type: 'START' }); const timerRace = race({ stop: take('STOP'), timer: call(delay, ONE_SECOND), }); expect(next).toEqual(timerRace); // let's trigger stop before the timer completes next = generator.next({ type: 'STOP' }); // we expect the runTimer to be awaiting a START action now expect(next).toEqual(take('START')); });
  • 12. Common uses - API calls - Data sync - Business logic services - Orchestration of components across multiple screens in your applications
  • 13. Summary IMO despite being initially intimidating, expressing asynchronous logic in sagas feels very natural, and is very powerful.
  • 14. pedro@8fit.com pssssssst! upgrade your life! come work with these beautiful people Thanks for listening ❤