Introduction to Redux-Saga
IntroductionIn this article I am going to introduce you to redux-saga . Redux-saga is a library that aims to manage application side effects.
The mental model is that a saga is like a separate thread in your application that's solely responsible for side effects. redux-saga is a redux middleware, which means this thread can be started, paused and cancelled from the main application with normal redux actions, it has access to the full redux application state and it can dispatch redux actions as well .
It uses an ES6 feature called Generators to make those asynchronous flows easy to read, write and test. I thoroughly recommend you to read more about generators before getting into sagas.
WorkshopWell, we are going to implement a simple application using redux-saga this time. The basic scaffolding of our app once built would be like this.
You may find the source code of this project on github . Let me just show you the sagas first. Here’s the code for our sagas.
It uses ES6 generators to pause and resume the execution allowing other code to run during these paused periods. Here we create a Saga that watches for all STUDENTS_FETCH_REQUESTED actions and triggers an API call to fetch the students data. When it is successfully completed, it dispatches STUDENTS_FETCH_SUCCEEDED action. Upon failure, it merely dispatches STUDENTS_FETCH_FAILED action to the store.
To run our Saga, we'll have to connect it to the Redux Store using the redux-saga middleware. Here’s the code snippet responsible for that.
Also note that here we mount the saga middleware on the store. Now our actions looks like this.
See how pure our actions are. They are now free from any side effects. This is much more easier to test since mocking is not needed.
SummaryIn this session we covered a lot of ground about redux-saga. You might've used redux-thunk before to handle your data fetching. Contrary to redux thunk, you don't end up in callback hell, you can test your asynchronous flows easily and your actions stay pure. Redux observable  is a similar library which handles side effects using Rx-JS.
The most important advice I can give is not to bring in either of these libraries before you need them. If you're only making simple ajax calls, you probably don't need them. redux-thunk is stupid simple to learn and provides enough for the basics, but the more complex the async the harder (or even impossible) it becomes for redux-thunk. But for redux-saga or redux-observable in many ways it shines the most the more complex the async is. 
Well, that does it for introduction to redux-saga. I’ll see you next time.