Redux-saga is a redux middleware library which designed for handling side effects in redux applications. It provides developers with the ability to manage asynchronous code synchronously.
Overview
redux-saga middleware sits on top of redux applications, between actions and reducers more specifically. It mitigates application state transitions and side effects. As a result, flows are easier to manage, more efficient to execute, easier to test, and better at handling failures.
Use Case
Fetching data from API can be a common use case for using redux-saga for handling side effects while the app is running in the background. This task is asynchronous as we can't be 100% sure if and when promised data will be available for our use. That results in poor user experience as we cannot guarantee the time it would take to display the data they need. By using a saga, we can stop function execution and wait until the data is ready, and then move forward to execute the next line of code. As [tag:redux saga], we'll usually want to display a loading indicator for signaling the status of the call to our users, resulting in better user experience at the end.
Example
function fetchJson(url) {
return fetch(url)
.then(request => request.text())
.then(text => {
return JSON.parse(text);
})
.catch(error => {
console.log(`ERROR: ${error.stack}`);
});
}
can be written as (with the help of libraries such as co.js)—
function * fetchJson(url) {
try {
let request = yield fetch(url);
let text = yield request.text();
return JSON.parse(text);
}
catch (error) {
console.log(`ERROR: ${error.stack}`);
}
};
Resources
- Redux-Saga Homepage
- Applying the Saga Pattern (Youtube video) By Caitie McCaffrey
- Original paper By Hector Garcia-Molina & Kenneth Salem
- A Saga on Sagas from MSDN site