Redux Saga

RapidAdminReact® uses Redux Saga for managing asynchronous action such as sending a request to your API. Since its integrated you don't need to do any setup and you can start creating sagas immediately.

Step1: Creating a new Saga

Once you have created your reducer and your actions, the next thing you might want for your asynchronous API requests, is a redux saga. You can simply create a new saga by creating a new file in src/store/sagas. You can classify your sagas in directory structure as per your requirement. This is how a sample saga would loook like:

import {put, takeEvery} from 'redux-saga/effects';
import * as actionTypes from '../../actionTypes';
import axiosBaseInstance from "../../../config/axios/axiosBaseInstance";
import {loginUser, loginFail} from '../../actions';

export function* loginSaga(action)
{
    try
    {
        const response = yield axiosBaseInstance.post('login', {
            email: action.email,
            password: action.password
        });
        if (response.data.status === 1)
        {
            yield window.accessToken = response.data.accessToken;
            yield put(loginUser(response));
        }
        else
        {
            yield put(loginFail(response));
        }
    } catch (errors)
    {
        yield put(loginFail(errors));
    }
}

export function* watchInitiateLogin()
{
    yield takeEvery(actionTypes.INITIATE_LOGIN, loginSaga);
}

Tips

  • Here we use the Action Creators
  • actionTypes help us maintain the consistency
  • Your API request logic remains in one file
  • We use generator functions to complete the asynchronous
  • You can read more abour Redux Saga Here

Adding your saga to the root Saga

Once you have created a saga it is mandatory for you to import this into root saga so that your saga is listening for the actions that you have created. Import your saga into the root saga file located at src/store/rootSaga.js

import { fork } from 'redux-saga/effects';
import { watchInitiateLogin } from './sagas/userSagas/userLogin';
//import (saga2);
//import (saga3);

export default function* rootSaga ()
{
    yield fork ( watchInitiateLogin );
    //yield fork(saga2);
	//yield fork(saga3);
}

You can import as many sagas as you create like this into this file.


Axios