Implementing redux-saga middleware in react

We cover how to integrate redux in react application on our previous article. Now we will cover how to implement side effects in this article.

redux-saga is the library which help to implement side effect in react application.(e.g asynchronous tasks like submitting form data to server, fetching data from API etc.)

Install

npm i redux-saga --save

OR

yarn add redux-saga

Usage Example

class LoginComponent extends React.Component {
  ...
  onLogin() {
    const { email, password, dispatch } = this.props
    dispatch({type: 'LOGIN_REQUESTED', payload: {email, password}})
  }
  ...
}

This LoginComponent dispatching login request, Now we'll implement saga which listen the type LOGIN_REQUEST and sending credentials to server for validate.

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

// Login Saga: this will be fired on LOGIN_REQUESTED actions
function* onLogin(action) {
   try {
      const credentials = yield call(Api.login, action.payload);
      yield put({type: "LOGIN_SUCCEEDED", credentials: credentials});
   } catch (e) {
      yield put({type: "LOGIN_FAILED", message: e.message});
   }
}

/*
  Starts login on each dispatched `LOGIN_REQUESTED` action.
*/
function* login() {
  yield takeEvery("LOGIN_REQUESTED", onLogin);
}

export default LoginSaga;

To make saga working we have to connect saga to Redux store using redux-saga middleware.

app.js
import { createStore, applyMiddleware } from 'redux';
import createSagaMiddleware from 'redux-saga';

import reducer from './reducers';
import LoginSaga from './sagas';

// create the saga middleware
const sagaMiddleware = createSagaMiddleware();

// mount it on the Store
const store = createStore(
  reducer,
  applyMiddleware(sagaMiddleware)
);

// then run the saga
sagaMiddleware.run(LoginSaga);

// render the application