redux-saga is a library that aims to make side effects (i.e. asynchronous things like data fetching and impure things like accessing the browser cache) in React/Redux applications easier and better.
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.
Source: https://redux-saga.github.io/redux-saga/index.html
Introduction
In short, redux-saga is about creating listeners for events (redux action).
Three parts of Sagas:
- Worker saga
- Watcher saga
- Root saga
Worker
saga example, do work and trigger state update
import axios from 'axios';
import { call, put } from 'redux-saga';
export function* createLessonAsync(action) {
try {
// call api
const response = yield call(axios.get, '...');
// dispatch action to store (handled by reducer)
yield put({type: 'lessons/CREATED', response: response.data})
} catch (e) {
// handle exception
yield put({type: 'lessons/CREATE_FAILED', message: e})
}
}
Watcher
saga example, spawn a new task on each action
import { takeEvery } from 'redux-saga';
export function* watchCreateLesson() {
// listen to 'lessons/CREATE' action and call createLessonAsync worker
yield takeEvery('lessons/CREATE', createLessonAsync);
}
take
/ takeEvery
effects is to wait for specific actions in the store.
Root
saga example, single entry point of starting all sagas
export default function* rootSaga() {
yield [
watchCreateLesson()
]
}