public.ts 1.49 KB
Newer Older
Viacheslav Pavlov's avatar
Viacheslav Pavlov committed
1
2
import Crop from 'model/Crop';
import {CropService} from 'service/CropService';
3
import {LOAD_CROPS_CACHE_IDLE, RECEIVE_CROPS} from 'crop/constants';
Viacheslav Pavlov's avatar
Viacheslav Pavlov committed
4
5
6
7
8
9
10
11
12
import {IReducerAction} from 'model/common.model';
import {log} from 'utilities/debug';


const receiveCrops = (crops: Crop[]): IReducerAction => ({
    type: RECEIVE_CROPS, payload: crops,
});

export const loadCrops = (forceReload: boolean = false) => (dispatch, getState) => {
13
14

    const timeSinceLastFetch = getState().crop.public.lastFetched;
Viacheslav Pavlov's avatar
Viacheslav Pavlov committed
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48

    // perform the API call if the data is older than the allowed limit
    const isDataStale = Date.now() - timeSinceLastFetch > LOAD_CROPS_CACHE_IDLE;

    if (isDataStale || forceReload) {
        return CropService.listCrops(getState().login.access_token)
            .then((list) => {
                dispatch(receiveCrops(list));
            })
            .catch((error) => {
                log('Error', error);
            });
    }
};

export const saveCrop = (crop: Crop) => (dispatch, getState) => {

    return CropService.saveCrop(getState().login.access_token, crop)
        .then(() => {
            dispatch(loadCrops(true));
        }).catch((error) => {
            log('Save error', error);
        });
};

export const deleteCrop = (crop: Crop) => (dispatch, getState) => {
    return CropService.deleteCrop(getState().login.access_token, crop.shortName)
        .then(() => {
            dispatch(loadCrops(true));
        })
        .catch((error) => {
            log('Error', error);
        });
};