Redux

Redux

Redux has been used as state management solution with redux-thunk for side-effects.
Every feature is organized in a folder containing three fundamental atomic part of redux flow as three separate file: actions, reducer, actionCreators for better structure.
For asynchronous state operations, well opinionated three actions model has been used. And the actions consist of [state]\_BEGIN,[state]\_SUCCESS,[state]\_FAILED.

Locate the redux folder in src/redux

Action

action.js file contains of all action types and payload required for any apps. Below is an example of authentication.


const actions = {
  LOGIN_BEGIN: 'LOGIN_BEGIN',
  LOGIN_SUCCESS: 'LOGIN_SUCCESS',
  LOGIN_ERR: 'LOGIN_ERR',

  loginBegin: () => {
    return {
      type: actions.LOGIN_BEGIN,
    };
  },

  loginSuccess: data => {
    return {
      type: actions.LOGIN_SUCCESS,
      data,
    };
  },

  loginErr: err => {
    return {
      type: actions.LOGIN_ERR,
      err,
    };
  },
};

export default actions;
                                                    
ActionCreator

Create all the actions declared in action.js file and pass the data in actionCreator.js file


import actions from './actions';

const { loginBegin, loginSuccess, loginErr } = actions;

const login = () => {
  return async dispatch => {
    try {
      dispatch(loginBegin());
      window.localStorage.setItem('logedIn', true);
      return dispatch(loginSuccess(true));
    } catch (err) {
      dispatch(loginErr(err));
    }
  };
};

export { login };
                                                    
Reducers

reducers.js file receives type and data from actionCreator.js file and return the data as state according to type.


import actions from './actions';

const { LOGIN_BEGIN, LOGIN_SUCCESS, LOGIN_ERR } = actions;

const initState = {
  login: window.localStorage.getItem('logedIn'),
  loading: false,
  error: null,
};

const AuthReducer = (state = initState, action) => {
  const { type, data, err } = action;
  switch (type) {
    case LOGIN_BEGIN:
      return {
        ...state,
        loading: true,
      };
    case LOGIN_SUCCESS:
      return {
        ...state,
        login: data,
        loading: false,
      };
    case LOGIN_ERR:
      return {
        ...state,
        error: err,
        loading: false,
      };
    default:
      return state;
  }
};
export default AuthReducer;
                                                    
rootReducers.js

Finally locate the rootReducers.js file from src/redux/rootReducers.js. Import the reducer here from reducers.js file and pass it as state.


import { combineReducers } from 'redux';
import authReducer from './authentication/reducers';

const rootReducers = combineReducers({
  auth: authReducer,
});

export default rootReducers;