Redux: A Modern Saga
For those of you who program in React, you know Redux is a framework that is built on top of React to increase the scalability of the project. But have you heard of Redux Saga?
Redux Saga is a middleware built to make application side effects more efficient. The side effects include data fetching, accessing browser cache, and other asynchronous tasks. Last publish two months ago, Redux Saga has 64 versions and a weekly average of 500,000 downloads.
This middleware’s role is to manage business process that involve multiple bounded contexts. A layer down, within the business process, are the interactions of multiple aggregates and multiple bounded contexts which are handled by a process manager.
An Aggregate: set of associated objects as a single unit for data changes
An example of such business process is when a customer is reserving a ticket online to a show — there would be an order aggregate, reservation aggregate, and payment aggregate, all of which are interacting and those interactions need to be handled by a process manager. This interaction is called a message and a message is usually made up of commands and events. This set up is typically seen in the use of a CQRS (Command Query Responsibility Segregation) pattern.
The benefit of using a process manager is that the aggregates no longer need to know about the next step in the process, they simply send and receive reports to and from the process manager. Secondly, all the messages flow to a single location.
When Should I Use a Process Manager?
- When the bounded context has a large number of events and commands (messages) that would be difficult to manage if the messages were being sent from aggregate to aggregate
- When routing between aggregates is important. A process manager can determine the routes.
How Do I Get Redux Saga?
Download the NPM package
npm install --save redux-saga
Import into your next project main.js file
How Do I Use Redux Saga?
Create a file called saga.js.
Add your generator function which will be used to make the action asynchronous later.
In main.js, create the middleware and connect it to Redux store.
Finally, create asynchronous calls in saga.js by taking in one action and calling another generator function that creates a new action and returns a value.
This new action must be accounted for in the reducer and must have a different name than the action the saga took in.
“MAKE_SAGA” vs “MAKE_SAGA_ASYNC”
To perform the asynchronous call or to test the Saga, follow along with this tutorial.
Redux Saga is similar to Redux-thunks, but avoids “callback hell” and async/await by using generators. It effectively handles data fetching and asynchronous calls and increases the efficiency of the communication between aggregates and bounded contexts. Testing Redux Saga is easier than thunks. Threads can be started, paused, and stopped through Redux actions.
To Learn More, Visit the Docs!