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

What's hot (20)

PDF
React + Redux. Best practices
Clickky
 
PDF
Workshop 14: AngularJS Parte III
Visual Engineering
 
PDF
Intro to Redux | DreamLab Academy #3
DreamLab
 
PDF
React & Redux
Federico Bond
 
PDF
Workshop 17: EmberJS parte II
Visual Engineering
 
PDF
Workshop 23: ReactJS, React & Redux testing
Visual Engineering
 
PPTX
Better React state management with Redux
Maurice De Beijer [MVP]
 
PDF
Quick start with React | DreamLab Academy #2
DreamLab
 
PDF
Building React Applications with Redux
FITC
 
PDF
Evan Schultz - Angular Camp - ng2-redux
Evan Schultz
 
PPTX
ProvJS: Six Months of ReactJS and Redux
Thom Nichols
 
PDF
Let's Redux!
Joseph Chiang
 
PPTX
React hooks
Assaf Gannon
 
PDF
React lecture
Christoffer Noring
 
PDF
Redux with angular 2 - workshop 2016
Nir Kaufman
 
PPTX
Redux training
dasersoft
 
PDF
React redux
Michel Perez
 
PDF
React, Redux, ES2015 by Max Petruck
Maksym Petruk
 
PDF
Introduction to Redux
Ignacio Martín
 
PDF
React state managmenet with Redux
Vedran Blaženka
 
React + Redux. Best practices
Clickky
 
Workshop 14: AngularJS Parte III
Visual Engineering
 
Intro to Redux | DreamLab Academy #3
DreamLab
 
React & Redux
Federico Bond
 
Workshop 17: EmberJS parte II
Visual Engineering
 
Workshop 23: ReactJS, React & Redux testing
Visual Engineering
 
Better React state management with Redux
Maurice De Beijer [MVP]
 
Quick start with React | DreamLab Academy #2
DreamLab
 
Building React Applications with Redux
FITC
 
Evan Schultz - Angular Camp - ng2-redux
Evan Schultz
 
ProvJS: Six Months of ReactJS and Redux
Thom Nichols
 
Let's Redux!
Joseph Chiang
 
React hooks
Assaf Gannon
 
React lecture
Christoffer Noring
 
Redux with angular 2 - workshop 2016
Nir Kaufman
 
Redux training
dasersoft
 
React redux
Michel Perez
 
React, Redux, ES2015 by Max Petruck
Maksym Petruk
 
Introduction to Redux
Ignacio Martín
 
React state managmenet with Redux
Vedran Blaženka
 

Viewers also liked (19)

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

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

PPTX
Using Redux-Saga for Handling Side Effects
GlobalLogic Ukraine
 
PDF
Sagas Middleware Architecture
Mateusz Bosek
 
PDF
Better react/redux apps using redux-saga
Younes (omar) Meliani
 
PDF
Side effects-con-redux
Nicolas Quiceno Benavides
 
PPTX
Jump into React-Native (Class 5)
Waqqas Jabbar
 
PDF
Redux Saga - Under the hood
Waqqas Jabbar
 
PDF
Redux-Saga: managing side effects and impure stuff
Julien Viala
 
PDF
Keep your side-effects 
in the right place with 
redux observable
Viliam Elischer
 
PDF
The evolution of redux action creators
George Bukhanov
 
PPTX
React gsg presentation with ryan jung & elias malik
Lama K Banna
 
Using Redux-Saga for Handling Side Effects
GlobalLogic Ukraine
 
Sagas Middleware Architecture
Mateusz Bosek
 
Better react/redux apps using redux-saga
Younes (omar) Meliani
 
Side effects-con-redux
Nicolas Quiceno Benavides
 
Jump into React-Native (Class 5)
Waqqas Jabbar
 
Redux Saga - Under the hood
Waqqas Jabbar
 
Redux-Saga: managing side effects and impure stuff
Julien Viala
 
Keep your side-effects 
in the right place with 
redux observable
Viliam Elischer
 
The evolution of redux action creators
George Bukhanov
 
React gsg presentation with ryan jung & elias malik
Lama K Banna
 
Ad

Recently uploaded (20)

PDF
SIZING YOUR AIR CONDITIONER---A PRACTICAL GUIDE.pdf
Muhammad Rizwan Akram
 
DOCX
Cryptography Quiz: test your knowledge of this important security concept.
Rajni Bhardwaj Grover
 
PDF
Transforming Utility Networks: Large-scale Data Migrations with FME
Safe Software
 
PDF
Transcript: Book industry state of the nation 2025 - Tech Forum 2025
BookNet Canada
 
PDF
UiPath DevConnect 2025: Agentic Automation Community User Group Meeting
DianaGray10
 
PDF
Peak of Data & AI Encore AI-Enhanced Workflows for the Real World
Safe Software
 
PDF
Go Concurrency Real-World Patterns, Pitfalls, and Playground Battles.pdf
Emily Achieng
 
PPTX
COMPARISON OF RASTER ANALYSIS TOOLS OF QGIS AND ARCGIS
Sharanya Sarkar
 
PDF
NASA A Researcher’s Guide to International Space Station : Physical Sciences ...
Dr. PANKAJ DHUSSA
 
PDF
“NPU IP Hardware Shaped Through Software and Use-case Analysis,” a Presentati...
Edge AI and Vision Alliance
 
PPTX
Agentforce World Tour Toronto '25 - MCP with MuleSoft
Alexandra N. Martinez
 
PDF
How do you fast track Agentic automation use cases discovery?
DianaGray10
 
PPTX
Designing_the_Future_AI_Driven_Product_Experiences_Across_Devices.pptx
presentifyai
 
PDF
Reverse Engineering of Security Products: Developing an Advanced Microsoft De...
nwbxhhcyjv
 
PPT
Ericsson LTE presentation SEMINAR 2010.ppt
npat3
 
PDF
AI Agents in the Cloud: The Rise of Agentic Cloud Architecture
Lilly Gracia
 
PDF
UPDF - AI PDF Editor & Converter Key Features
DealFuel
 
PDF
Newgen Beyond Frankenstein_Build vs Buy_Digital_version.pdf
darshakparmar
 
PDF
“Computer Vision at Sea: Automated Fish Tracking for Sustainable Fishing,” a ...
Edge AI and Vision Alliance
 
PDF
NLJUG Speaker academy 2025 - first session
Bert Jan Schrijver
 
SIZING YOUR AIR CONDITIONER---A PRACTICAL GUIDE.pdf
Muhammad Rizwan Akram
 
Cryptography Quiz: test your knowledge of this important security concept.
Rajni Bhardwaj Grover
 
Transforming Utility Networks: Large-scale Data Migrations with FME
Safe Software
 
Transcript: Book industry state of the nation 2025 - Tech Forum 2025
BookNet Canada
 
UiPath DevConnect 2025: Agentic Automation Community User Group Meeting
DianaGray10
 
Peak of Data & AI Encore AI-Enhanced Workflows for the Real World
Safe Software
 
Go Concurrency Real-World Patterns, Pitfalls, and Playground Battles.pdf
Emily Achieng
 
COMPARISON OF RASTER ANALYSIS TOOLS OF QGIS AND ARCGIS
Sharanya Sarkar
 
NASA A Researcher’s Guide to International Space Station : Physical Sciences ...
Dr. PANKAJ DHUSSA
 
“NPU IP Hardware Shaped Through Software and Use-case Analysis,” a Presentati...
Edge AI and Vision Alliance
 
Agentforce World Tour Toronto '25 - MCP with MuleSoft
Alexandra N. Martinez
 
How do you fast track Agentic automation use cases discovery?
DianaGray10
 
Designing_the_Future_AI_Driven_Product_Experiences_Across_Devices.pptx
presentifyai
 
Reverse Engineering of Security Products: Developing an Advanced Microsoft De...
nwbxhhcyjv
 
Ericsson LTE presentation SEMINAR 2010.ppt
npat3
 
AI Agents in the Cloud: The Rise of Agentic Cloud Architecture
Lilly Gracia
 
UPDF - AI PDF Editor & Converter Key Features
DealFuel
 
Newgen Beyond Frankenstein_Build vs Buy_Digital_version.pdf
darshakparmar
 
“Computer Vision at Sea: Automated Fish Tracking for Sustainable Fishing,” a ...
Edge AI and Vision Alliance
 
NLJUG Speaker academy 2025 - first session
Bert Jan Schrijver
 

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 ❤