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 (10)

PPTX
Using Redux-Saga for Handling Side Effects
PDF
Sagas Middleware Architecture
PDF
Better react/redux apps using redux-saga
PDF
Side effects-con-redux
PPTX
Jump into React-Native (Class 5)
PDF
Redux Saga - Under the hood
PDF
Redux-Saga: managing side effects and impure stuff
PDF
Keep your side-effects 
in the right place with 
redux observable
PDF
The evolution of redux action creators
PPTX
React gsg presentation with ryan jung & elias malik
Using Redux-Saga for Handling Side Effects
Sagas Middleware Architecture
Better react/redux apps using redux-saga
Side effects-con-redux
Jump into React-Native (Class 5)
Redux Saga - Under the hood
Redux-Saga: managing side effects and impure stuff
Keep your side-effects 
in the right place with 
redux observable
The evolution of redux action creators
React gsg presentation with ryan jung & elias malik

Recently uploaded (20)

PDF
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
PDF
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
PDF
Approach and Philosophy of On baking technology
PPTX
ACSFv1EN-58255 AWS Academy Cloud Security Foundations.pptx
PDF
NewMind AI Weekly Chronicles - August'25-Week II
PDF
Reach Out and Touch Someone: Haptics and Empathic Computing
PDF
The Rise and Fall of 3GPP – Time for a Sabbatical?
PDF
Diabetes mellitus diagnosis method based random forest with bat algorithm
PDF
Unlocking AI with Model Context Protocol (MCP)
PDF
Spectral efficient network and resource selection model in 5G networks
PDF
cuic standard and advanced reporting.pdf
PDF
Building Integrated photovoltaic BIPV_UPV.pdf
PPTX
Spectroscopy.pptx food analysis technology
PPT
“AI and Expert System Decision Support & Business Intelligence Systems”
PPTX
Big Data Technologies - Introduction.pptx
PPTX
Programs and apps: productivity, graphics, security and other tools
PPTX
MYSQL Presentation for SQL database connectivity
PDF
Advanced methodologies resolving dimensionality complications for autism neur...
PPTX
Cloud computing and distributed systems.
PDF
MIND Revenue Release Quarter 2 2025 Press Release
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
Approach and Philosophy of On baking technology
ACSFv1EN-58255 AWS Academy Cloud Security Foundations.pptx
NewMind AI Weekly Chronicles - August'25-Week II
Reach Out and Touch Someone: Haptics and Empathic Computing
The Rise and Fall of 3GPP – Time for a Sabbatical?
Diabetes mellitus diagnosis method based random forest with bat algorithm
Unlocking AI with Model Context Protocol (MCP)
Spectral efficient network and resource selection model in 5G networks
cuic standard and advanced reporting.pdf
Building Integrated photovoltaic BIPV_UPV.pdf
Spectroscopy.pptx food analysis technology
“AI and Expert System Decision Support & Business Intelligence Systems”
Big Data Technologies - Introduction.pptx
Programs and apps: productivity, graphics, security and other tools
MYSQL Presentation for SQL database connectivity
Advanced methodologies resolving dimensionality complications for autism neur...
Cloud computing and distributed systems.
MIND Revenue Release Quarter 2 2025 Press Release

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 ❤