plustarReducer.js 2.21 KB
import * as types from '../constants/ActionTypes';

let initialState = {
    payload: {
        left: {
            loading: false,
            head: [],
            foot: [],
            data: [],
            segment: null,
        },
        right: {
            loading: false,
            head: [],
            foot: [],
            data: [],
            segment: null,
        },
        selectedIndex: 0,
        genderType: 0,
    },
    error: false,
};

export default function plustar(state=initialState, action) {
    switch(action.type) {
        case types.REQUEST_PLASTAR_DATA: {
            return Object.assign({}, state, {
                payload: loadingPayload(state.payload, action, true)
            });
        }
            
        case types.RECEIVE_PLASTAR_DATA: {
            
            if(action.error) {
                return Object.assign({}, state, {
                    payload: loadingPayload(state.payload, action, false),
                    error: action.error,
                });
            }

            return Object.assign({}, state, {
                payload: dataPayload(state.payload, action)
            });
        }

        case types.SWITCH_SEGMENT: {

            let payload = Object.assign({}, state.payload, {
                selectedIndex: action.payload.selectedIndex,
            });

            return Object.assign({}, state, {
                payload: payload
            });
        }

        case types.SWITCH_GENDER: {

            let payload = Object.assign({}, state.payload, {
                genderType: action.payload.genderType,
            });

            return Object.assign({}, state, {
                payload: payload
            });
        }

        default:
            return state;
    }
}

function loadingPayload(payload, action, loading) {
    
    let newPayload = Object.assign({}, payload, {
        [action.payload.selectedItem]: Object.assign({}, payload[action.payload.selectedItem], {
            loading,
        }),
    });

    return newPayload;
}

function dataPayload(payload, action) {

    let newPayload = Object.assign({}, payload, {
        [action.payload.selectedItem]: action.payload[action.payload.selectedItem],
    });

    return newPayload;
}