SlideShare a Scribd company logo
1 of 22
Download to read offline
Sagas middleware architecture
Mateusz Bosek
Types of middlewares
redux-thunk
It allows to write action
creators that return a
function instead of an
action. The thunk can be
used to delay the dispatch
of an action or to dispatch
only if a certain condition is
met. 

redux-saga

It aims to make the
execution of application side
effects (e.g., asynchronous
tasks like data fetching and
impure procedures such as
accessing the browser
cache) manageable and
efficient. It uses the ES6
feature called generators,
making the flow easy to
read as synchronous code.


redux-observable

Inspired by redux-thunk
allows developers to
dispatch a function that
returns an Observable,
Promise or iterable of
action(s). When the
observable emits an action,
or the promise resolves an
action, or the iterable gives
an action out, that action is
then dispatched as usual.
Comparing middlewares

1. redux-thunk
Comparing middlewares

1. redux-thunk
Thunks begin running into hurdles once more complex sequences
of asynchronous flows are required

A thunk must utilize getState(), increasing the complexity and
functional impurity of your thunk

A component calling the thunk needs additional state and logic to
make these decisions, which can quickly break DRY principles
The most-widely adopted and simplest of the middlewares

Actions can not only be small objects, but functions as well
Comparing middlewares

1. redux-thunk
Comparing middlewares

1. redux-thunk
Comparing middlewares

1. redux-sagas p.1
Uses generators

Easily tracking and orchestrating asynchronous processes in
synchronous looking code

Allows for fairly complicated flows

Many helpers, effects and solid doc

Action creators stays pure

Sagas are composable

Simpler error handling
Comparing middlewares

1. redux-sagas p.2
The runtime which is 20kb+ minified and gzipped - nearly as big
as React or jQuery

Sagas always receive actions after reducers

Requires the steepest learning curve

Carefully consider what needs to be a side effect and what should
really be a pure state transformation.

Easy to test without mocking

Isolates side-effect code to a single area of app
Comparing middlewares

1. redux-observables
Requires the steepest learning curve

Observables offer a great combination of a comprehensive API

Testability

Functional purity

Ability to perform complex asynchronous patterns

Inspired by redux-saga
What is saga?




Sagas are responsible for orchestrating complex/asynchronous
operations.

Sagas are created using Generator functions.

Redux-saga's goal is to provide a mechanism for orchestrating
complex async operations with Redux.
What is saga?
Generator function*




Generators are functions that can be exited and later re-entered.
Their context will be saved across re-entrances


Generators are cooperative which means that it chooses when it will
allow and interruption so that it can cooperate with the rest of your
program

function* foo() {

yield takeEvery('FETCH_PRODUCTS_REQUESTED', fetchProducts);

}
yield
The yield expression is used to pause the function and give out a
value

yield can also take in value when we restart the function

yield* is used to delegate to another outside generator function
How to run the function*
Invoke the function and store it as a variable

The invocation of the function returs an iterable object back to us

Call next on this object to take us to the first yield point in the
function

This call will give us back an object with the properties of value and
done

We can continue iterating through this until we are done or stop at
any point
How to run the function*
Watchers, workers, effects
Watchers
export function* watchFetchProducts() {

yield takeEvery('FETCH_PRODUCTS_REQUEST', fetchProducts);

}
Watchers, workers, effects
Workers
export function* fetchAllProducts(action) {

try {

const data = yield call(Api.fetchUser, action.payload.url)

yield put({ type: "FETCH_USERS_SUCCESS", data })

} catch (error) {

yield put({ type: "FETCH_USERS_FAIL", error })

}

}
Watchers, workers, effects
Effects
call - runs a function, returns a promise, pauses the saga until the promise is
resolved

put - dispatch an action


Others:

fork, select, race, spawn, join, cancel
Async/await vs redux-saga
Async/await vs redux-saga
Saga being an interpreter of effects is granting us the full control of how and
when those effects are resolved + effects are just simple object which are
easily comparable and can be monitored which is also way harder with
Promises.


Where do u see a steep learning curve with redux-saga? Could something
be done to ease that? As to the syntax they both (async and generators) are
pretty much the same - just using other keywords. What is done under the
hood completely different, but this knowledge is not really that much
needed for beginners.
Testing
function* startForeman() {

	yield fork(startTranspiler);

	yield fork(startLinter);

}
Testing
describe('sagas/foreman', () => {

const generator = startForeman();


it('forks the transpiler process', () => {

const result = generator.next();

expect(result.value).to.deep.equal(fork(foreman.startTranspiler))

});


it('forks the linter process', () => {

const result = generator.next();

expect(result.value).to.deep.equal(fork(foreman.startLinter))

});

})
https://redux-saga.js.org/


https://medium.com/@lavitr01051977/make-your-first-call-to-api-usi
ng-redux-saga-15aa995df5b6


https://medium.com/@totaldis/redux-saga-in-action-s-f7d11cffa35a
mateusz.bosek@hubranch.com
Private and company consultation

THANK YOU

More Related Content

What's hot

React + Redux Introduction
React + Redux IntroductionReact + Redux Introduction
React + Redux IntroductionNikolaus Graf
 
RxJS + Redux + React = Amazing
RxJS + Redux + React = AmazingRxJS + Redux + React = Amazing
RxJS + Redux + React = AmazingJay Phelps
 
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...Domenic Denicola
 
Spring batch introduction
Spring batch introductionSpring batch introduction
Spring batch introductionAlex Fernandez
 
Lambda Expressions in Java 8
Lambda Expressions in Java 8Lambda Expressions in Java 8
Lambda Expressions in Java 8icarter09
 
Angular and The Case for RxJS
Angular and The Case for RxJSAngular and The Case for RxJS
Angular and The Case for RxJSSandi Barr
 
Javascript Arrow function
Javascript Arrow functionJavascript Arrow function
Javascript Arrow functiontanerochris
 
Monoids - Part 1 - with examples using Scalaz and Cats
Monoids - Part 1 - with examples using Scalaz and CatsMonoids - Part 1 - with examples using Scalaz and Cats
Monoids - Part 1 - with examples using Scalaz and CatsPhilip Schwarz
 
Rethinking Best Practices
Rethinking Best PracticesRethinking Best Practices
Rethinking Best Practicesfloydophone
 
Hibernate architecture
Hibernate architectureHibernate architecture
Hibernate architectureAnurag
 
Reactive Programming for a demanding world: building event-driven and respons...
Reactive Programming for a demanding world: building event-driven and respons...Reactive Programming for a demanding world: building event-driven and respons...
Reactive Programming for a demanding world: building event-driven and respons...Mario Fusco
 

What's hot (20)

React / Redux Architectures
React / Redux ArchitecturesReact / Redux Architectures
React / Redux Architectures
 
Java 8 Workshop
Java 8 WorkshopJava 8 Workshop
Java 8 Workshop
 
React + Redux Introduction
React + Redux IntroductionReact + Redux Introduction
React + Redux Introduction
 
React & Redux
React & ReduxReact & Redux
React & Redux
 
RxJS + Redux + React = Amazing
RxJS + Redux + React = AmazingRxJS + Redux + React = Amazing
RxJS + Redux + React = Amazing
 
react redux.pdf
react redux.pdfreact redux.pdf
react redux.pdf
 
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...
 
Spring batch introduction
Spring batch introductionSpring batch introduction
Spring batch introduction
 
Lambda Expressions in Java 8
Lambda Expressions in Java 8Lambda Expressions in Java 8
Lambda Expressions in Java 8
 
Angular and The Case for RxJS
Angular and The Case for RxJSAngular and The Case for RxJS
Angular and The Case for RxJS
 
Javascript Arrow function
Javascript Arrow functionJavascript Arrow function
Javascript Arrow function
 
Spring batch
Spring batchSpring batch
Spring batch
 
Monoids - Part 1 - with examples using Scalaz and Cats
Monoids - Part 1 - with examples using Scalaz and CatsMonoids - Part 1 - with examples using Scalaz and Cats
Monoids - Part 1 - with examples using Scalaz and Cats
 
Ngrx slides
Ngrx slidesNgrx slides
Ngrx slides
 
Preparing for Scala 3
Preparing for Scala 3Preparing for Scala 3
Preparing for Scala 3
 
Rethinking Best Practices
Rethinking Best PracticesRethinking Best Practices
Rethinking Best Practices
 
Introduction to Data Oriented Design
Introduction to Data Oriented DesignIntroduction to Data Oriented Design
Introduction to Data Oriented Design
 
Hibernate architecture
Hibernate architectureHibernate architecture
Hibernate architecture
 
Reactive Programming for a demanding world: building event-driven and respons...
Reactive Programming for a demanding world: building event-driven and respons...Reactive Programming for a demanding world: building event-driven and respons...
Reactive Programming for a demanding world: building event-driven and respons...
 
Rxjs ngvikings
Rxjs ngvikingsRxjs ngvikings
Rxjs ngvikings
 

Similar to Sagas Middleware Architecture

JSON Part 3: Asynchronous Ajax & JQuery Deferred
JSON Part 3: Asynchronous Ajax & JQuery DeferredJSON Part 3: Asynchronous Ajax & JQuery Deferred
JSON Part 3: Asynchronous Ajax & JQuery DeferredJeff Fox
 
A React Journey
A React JourneyA React Journey
A React JourneyLinkMe Srl
 
Introduction to Redux (for Angular and React devs)
Introduction to Redux (for Angular and React devs)Introduction to Redux (for Angular and React devs)
Introduction to Redux (for Angular and React devs)Fabio Biondi
 
React js programming concept
React js programming conceptReact js programming concept
React js programming conceptTariqul islam
 
Asynchronous development in JavaScript
Asynchronous development  in JavaScriptAsynchronous development  in JavaScript
Asynchronous development in JavaScriptAmitai Barnea
 
A full introductory guide to React
A full introductory guide to ReactA full introductory guide to React
A full introductory guide to ReactJean Carlo Emer
 
Introduction to Actor Model and Akka
Introduction to Actor Model and AkkaIntroduction to Actor Model and Akka
Introduction to Actor Model and AkkaYung-Lin Ho
 
Workshop 22: React-Redux Middleware
Workshop 22: React-Redux MiddlewareWorkshop 22: React-Redux Middleware
Workshop 22: React-Redux MiddlewareVisual Engineering
 
Workshop 22: ReactJS Redux Advanced
Workshop 22: ReactJS Redux AdvancedWorkshop 22: ReactJS Redux Advanced
Workshop 22: ReactJS Redux AdvancedVisual Engineering
 
Corso su ReactJS
Corso su ReactJSCorso su ReactJS
Corso su ReactJSLinkMe Srl
 
The Mayans Lost Guide to RxJava on Android
The Mayans Lost Guide to RxJava on AndroidThe Mayans Lost Guide to RxJava on Android
The Mayans Lost Guide to RxJava on AndroidFernando Cejas
 
Unit Testing Express and Koa Middleware in ES2015
Unit Testing Express and Koa Middleware in ES2015Unit Testing Express and Koa Middleware in ES2015
Unit Testing Express and Koa Middleware in ES2015Morris Singer
 
What is new in java 8 concurrency
What is new in java 8 concurrencyWhat is new in java 8 concurrency
What is new in java 8 concurrencykshanth2101
 
Effective JavaFX architecture with FxObjects
Effective JavaFX architecture with FxObjectsEffective JavaFX architecture with FxObjects
Effective JavaFX architecture with FxObjectsSrikanth Shenoy
 
Java concurrency model - The Future Task
Java concurrency model - The Future TaskJava concurrency model - The Future Task
Java concurrency model - The Future TaskSomenath Mukhopadhyay
 

Similar to Sagas Middleware Architecture (20)

JSON Part 3: Asynchronous Ajax & JQuery Deferred
JSON Part 3: Asynchronous Ajax & JQuery DeferredJSON Part 3: Asynchronous Ajax & JQuery Deferred
JSON Part 3: Asynchronous Ajax & JQuery Deferred
 
A React Journey
A React JourneyA React Journey
A React Journey
 
Introduction to Redux (for Angular and React devs)
Introduction to Redux (for Angular and React devs)Introduction to Redux (for Angular and React devs)
Introduction to Redux (for Angular and React devs)
 
Akka (1)
Akka (1)Akka (1)
Akka (1)
 
React js programming concept
React js programming conceptReact js programming concept
React js programming concept
 
Asynchronous development in JavaScript
Asynchronous development  in JavaScriptAsynchronous development  in JavaScript
Asynchronous development in JavaScript
 
A full introductory guide to React
A full introductory guide to ReactA full introductory guide to React
A full introductory guide to React
 
Introduction to Actor Model and Akka
Introduction to Actor Model and AkkaIntroduction to Actor Model and Akka
Introduction to Actor Model and Akka
 
Workshop 22: React-Redux Middleware
Workshop 22: React-Redux MiddlewareWorkshop 22: React-Redux Middleware
Workshop 22: React-Redux Middleware
 
Workshop 22: ReactJS Redux Advanced
Workshop 22: ReactJS Redux AdvancedWorkshop 22: ReactJS Redux Advanced
Workshop 22: ReactJS Redux Advanced
 
Corso su ReactJS
Corso su ReactJSCorso su ReactJS
Corso su ReactJS
 
Redux
ReduxRedux
Redux
 
The Mayans Lost Guide to RxJava on Android
The Mayans Lost Guide to RxJava on AndroidThe Mayans Lost Guide to RxJava on Android
The Mayans Lost Guide to RxJava on Android
 
Redux workshop
Redux workshopRedux workshop
Redux workshop
 
Unit Testing Express and Koa Middleware in ES2015
Unit Testing Express and Koa Middleware in ES2015Unit Testing Express and Koa Middleware in ES2015
Unit Testing Express and Koa Middleware in ES2015
 
MobX for dummies
MobX for dummiesMobX for dummies
MobX for dummies
 
G pars
G parsG pars
G pars
 
What is new in java 8 concurrency
What is new in java 8 concurrencyWhat is new in java 8 concurrency
What is new in java 8 concurrency
 
Effective JavaFX architecture with FxObjects
Effective JavaFX architecture with FxObjectsEffective JavaFX architecture with FxObjects
Effective JavaFX architecture with FxObjects
 
Java concurrency model - The Future Task
Java concurrency model - The Future TaskJava concurrency model - The Future Task
Java concurrency model - The Future Task
 

Recently uploaded

Benefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksBenefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksSoftradix Technologies
 
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Wonjun Hwang
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticscarlostorres15106
 
Unlocking the Potential of the Cloud for IBM Power Systems
Unlocking the Potential of the Cloud for IBM Power SystemsUnlocking the Potential of the Cloud for IBM Power Systems
Unlocking the Potential of the Cloud for IBM Power SystemsPrecisely
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machinePadma Pradeep
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
Bluetooth Controlled Car with Arduino.pdf
Bluetooth Controlled Car with Arduino.pdfBluetooth Controlled Car with Arduino.pdf
Bluetooth Controlled Car with Arduino.pdfngoud9212
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions
 
Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptxLBM Solutions
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr LapshynFwdays
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024The Digital Insurer
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...Fwdays
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersThousandEyes
 

Recently uploaded (20)

E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptxE-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
 
Benefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksBenefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other Frameworks
 
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
 
Unlocking the Potential of the Cloud for IBM Power Systems
Unlocking the Potential of the Cloud for IBM Power SystemsUnlocking the Potential of the Cloud for IBM Power Systems
Unlocking the Potential of the Cloud for IBM Power Systems
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machine
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
Vulnerability_Management_GRC_by Sohang Sengupta.pptx
Vulnerability_Management_GRC_by Sohang Sengupta.pptxVulnerability_Management_GRC_by Sohang Sengupta.pptx
Vulnerability_Management_GRC_by Sohang Sengupta.pptx
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
Bluetooth Controlled Car with Arduino.pdf
Bluetooth Controlled Car with Arduino.pdfBluetooth Controlled Car with Arduino.pdf
Bluetooth Controlled Car with Arduino.pdf
 
DMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special EditionDMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special Edition
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food Manufacturing
 
Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptx
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
 

Sagas Middleware Architecture

  • 2. Types of middlewares redux-thunk It allows to write action creators that return a function instead of an action. The thunk can be used to delay the dispatch of an action or to dispatch only if a certain condition is met. redux-saga It aims to make the execution of application side effects (e.g., asynchronous tasks like data fetching and impure procedures such as accessing the browser cache) manageable and efficient. It uses the ES6 feature called generators, making the flow easy to read as synchronous code. redux-observable Inspired by redux-thunk allows developers to dispatch a function that returns an Observable, Promise or iterable of action(s). When the observable emits an action, or the promise resolves an action, or the iterable gives an action out, that action is then dispatched as usual.
  • 3. Comparing middlewares 1. redux-thunk Comparing middlewares 1. redux-thunk Thunks begin running into hurdles once more complex sequences of asynchronous flows are required A thunk must utilize getState(), increasing the complexity and functional impurity of your thunk A component calling the thunk needs additional state and logic to make these decisions, which can quickly break DRY principles The most-widely adopted and simplest of the middlewares Actions can not only be small objects, but functions as well
  • 5. Comparing middlewares 1. redux-sagas p.1 Uses generators Easily tracking and orchestrating asynchronous processes in synchronous looking code Allows for fairly complicated flows Many helpers, effects and solid doc Action creators stays pure Sagas are composable Simpler error handling
  • 6. Comparing middlewares 1. redux-sagas p.2 The runtime which is 20kb+ minified and gzipped - nearly as big as React or jQuery Sagas always receive actions after reducers Requires the steepest learning curve Carefully consider what needs to be a side effect and what should really be a pure state transformation. Easy to test without mocking Isolates side-effect code to a single area of app
  • 7. Comparing middlewares 1. redux-observables Requires the steepest learning curve Observables offer a great combination of a comprehensive API Testability Functional purity Ability to perform complex asynchronous patterns Inspired by redux-saga
  • 8. What is saga? Sagas are responsible for orchestrating complex/asynchronous operations. Sagas are created using Generator functions. Redux-saga's goal is to provide a mechanism for orchestrating complex async operations with Redux.
  • 10. Generator function* Generators are functions that can be exited and later re-entered. Their context will be saved across re-entrances Generators are cooperative which means that it chooses when it will allow and interruption so that it can cooperate with the rest of your program function* foo() { yield takeEvery('FETCH_PRODUCTS_REQUESTED', fetchProducts); }
  • 11. yield The yield expression is used to pause the function and give out a value yield can also take in value when we restart the function yield* is used to delegate to another outside generator function
  • 12. How to run the function* Invoke the function and store it as a variable The invocation of the function returs an iterable object back to us Call next on this object to take us to the first yield point in the function This call will give us back an object with the properties of value and done We can continue iterating through this until we are done or stop at any point
  • 13. How to run the function*
  • 14. Watchers, workers, effects Watchers export function* watchFetchProducts() { yield takeEvery('FETCH_PRODUCTS_REQUEST', fetchProducts); }
  • 15. Watchers, workers, effects Workers export function* fetchAllProducts(action) {
 try { const data = yield call(Api.fetchUser, action.payload.url) yield put({ type: "FETCH_USERS_SUCCESS", data }) } catch (error) { yield put({ type: "FETCH_USERS_FAIL", error }) } }
  • 16. Watchers, workers, effects Effects call - runs a function, returns a promise, pauses the saga until the promise is resolved put - dispatch an action Others: fork, select, race, spawn, join, cancel
  • 18. Async/await vs redux-saga Saga being an interpreter of effects is granting us the full control of how and when those effects are resolved + effects are just simple object which are easily comparable and can be monitored which is also way harder with Promises. Where do u see a steep learning curve with redux-saga? Could something be done to ease that? As to the syntax they both (async and generators) are pretty much the same - just using other keywords. What is done under the hood completely different, but this knowledge is not really that much needed for beginners.
  • 19. Testing function* startForeman() { yield fork(startTranspiler); yield fork(startLinter); }
  • 20. Testing describe('sagas/foreman', () => { const generator = startForeman(); it('forks the transpiler process', () => { const result = generator.next(); expect(result.value).to.deep.equal(fork(foreman.startTranspiler)) }); it('forks the linter process', () => { const result = generator.next(); expect(result.value).to.deep.equal(fork(foreman.startLinter)) }); })