public.ts 1.37 KB
Newer Older
Viacheslav Pavlov's avatar
Viacheslav Pavlov committed
1 2 3
import update from 'immutability-helper';

import { IReducerAction } from 'model/common.model';
Viacheslav Pavlov's avatar
Viacheslav Pavlov committed
4
import {RECEIVE_CROP_DETAILS, RECEIVE_CROPS, ADMIN_RECEIVE_CROP} from 'crop/constants';
Viacheslav Pavlov's avatar
Viacheslav Pavlov committed
5 6

const INITIAL_STATE = {
7
    list: null,
Viacheslav Pavlov's avatar
Viacheslav Pavlov committed
8
    lastFetched: 0,
Viacheslav Pavlov's avatar
Viacheslav Pavlov committed
9
    details: null,
Viacheslav Pavlov's avatar
Viacheslav Pavlov committed
10 11 12 13 14 15 16
};

export default function crop(state = INITIAL_STATE, action: IReducerAction = {type: ''}) {

    switch (action.type) {
        case RECEIVE_CROPS: {
            return update(state, {
17
                list: {$set: action.payload},
Viacheslav Pavlov's avatar
Viacheslav Pavlov committed
18 19 20
                lastFetched: {$set: Date.now()},
            });
        }
Viacheslav Pavlov's avatar
Viacheslav Pavlov committed
21
        case ADMIN_RECEIVE_CROP: {
Viacheslav Pavlov's avatar
Viacheslav Pavlov committed
22
            const updateIndex = state.list && action.payload ? state.list.findIndex((crop) => crop.shortName === action.payload.shortName) : -1;
23 24 25 26

            return updateIndex === -1 ?
                update(state, {
                    details: {$set: null},
Viacheslav Pavlov's avatar
Viacheslav Pavlov committed
27
                    list: {$push: action.payload ? [action.payload] : []},
28 29 30 31 32 33 34 35 36
                })
                :
                update(state, {
                    details: {$set: null},
                    list: {
                        [updateIndex]: {$set: action.payload},
                    },
                });

Viacheslav Pavlov's avatar
Viacheslav Pavlov committed
37 38 39 40 41 42
        }
        case RECEIVE_CROP_DETAILS: {
            return update(state, {
                details: {$set: action.payload},
            });
        }
Viacheslav Pavlov's avatar
Viacheslav Pavlov committed
43 44 45 46 47 48

        default:
            return state;
    }

}