Redux-Saga is a middleware library which is handling async tasks with side effects, such as API. Also, we are able to read the state and call actions on Saga. It uses generator functions in order to do async tasks.

The following outlines why we use Saga and how to install it. Then, it is discussed useful Saga methods for handling API.

Why we are using the Redux-Saga?

Before working with Redux-Saga, you should be familiar with Redux.

For reading about Redux, click here.

How to install Redux-saga?

npm install redux-saga

or

yarn add redux-saga

Then, you need to create an example redux middleware. For example:

import { call, put, takeEvery } from 'redux-saga/effects'
import Api from '...'

function* fetchUser(action) {
try {
const user = yield call(Api.fetchUser, action.payload.userId);
yield put({type: "USER_FETCH_SUCCEEDED", user: user});
} catch (e) {
yield put({type: "USER_FETCH_FAILED", message: e.message});
}
}

function* mySaga() {
yield takeEvery("USER_FETCH_REQUESTED", fetchUser);
}

export default mySaga;

In the example, when USER_FETCH_REQUESTED action dispatched, it sends a call request to the API. In case of success, it dispatches an action with type USER_FETCH_SUCCEEDED with the user payload. Otherwise, in case of error status, it dispatches an action with the type USER_FETCH_FAILED and the error message payload.

The API can be something like this:

import axios from 'axios';

const Api = {
fetchUser: (userId) => {
return axios.get(`...?userId=${userId}`)
}
};

export default Api;

Next, you need to add your saga to the redux store:

import { createStore, applyMiddleware } from 'redux'
import createSagaMiddleware from 'redux-saga'

import reducer from './reducers'
import mySaga from './sagas'

const sagaMiddleware = createSagaMiddleware();

const store = createStore(
reducer,
applyMiddleware(sagaMiddleware)
);

sagaMiddleware.run(mySaga);

In the above code, the middleware of saga is created and applied to the store, finally, it runs.

Saga Methods

select

const userId = yield select(userSelectors.getUserId);

put

yield put({type: "USER_FETCH_SUCCEEDED", user: user});

call

const user = yield call(Api.fetchUser, action.payload.userId);

takeEvery

yield takeEvery("USER_FETCH_REQUESTED", fetchUser);

takeLatest

yield takeLatest("USER_FETCH_REQUESTED", fetchUser);

Conclusion

Web Developer

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store