Redux-Saga example

*redux-saga notes for me myself and i

Redux-saga are for asynchronous actions with side-effects

install

npm i redux-saga

root.reducer.js

import { combineReducers } from 'redux';
import { persistReducer } from 'redux-persist';

import userReducer from './user/user.reducer.js';

const rootReducer = combineReducers({
    user: userReducer,
});

export default rootReducer;

store.js

import createSagaMiddleware from 'redux-saga';
import rootSaga from './root-saga.js';

const sagaMiddleware = createSagaMiddleware();
const middleWares = [sagaMiddleware]
const store = createStore(rootReducer, applyMiddleware(...middleWares));
sagaMiddleware.run(rootSaga);

export default store;

root-saga.js

import { all, call } from 'redux-saga/effects';
import { userSagas } from './user/user.sagas.js';

export default function* rootSaga() {
    yield all([call(shopSagas), call(userSagas), call(cartSagas)]);
}

user.types.js

const UserActionTypes = {
    EMAIL_SIGN_IN_START: 'EMAIL_SIGN_IN_START',
    SIGN_IN_SUCCESS: 'SIGN_IN_SUCCESS',
    SIGN_IN_FAILURE: 'SIGN_IN_FAILURE',
};

export default UserActionTypes;

user.actions.js

import UserActionTypes from './user.types.js';

export const emailSignInStart = (emailAndPassword) => ({
    type: UserActionTypes.EMAIL_SIGN_IN_START,
    payload: emailAndPassword,
});

export const signInSuccess = (user) => ({
    type: UserActionTypes.SIGN_IN_SUCCESS,
    payload: user,
});

export const signInFailure = (error) => ({
    type: UserActionTypes.SIGN_IN_FAILURE,
    payload: error,
});

user.reducer.js

import UserActionTypes from './user.types';

const INITIAL_STATE = {
    currentUser: null,
    error: null,
};

const userReducer = (state = INITIAL_STATE, action) => {
    switch (action.type) {
        case UserActionTypes.SIGN_IN_SUCCESS:
            return {
                ...state,
                currentUser: action.payload,
                error: null,
            };

        case UserActionTypes.SIGN_IN_FAILURE:
            return {
                ...state,
                error: action.payload,
            };

        default:
            return state;
    }
};

export default userReducer;