Projekt

Obecné

Profil

Stáhnout (2.24 KB) Statistiky
| Větev: | Tag: | Revize:
1
import { createSlice } from '@reduxjs/toolkit'
2
import { CatalogItemDto } from '../../swagger/data-contracts'
3
import { fetchItems } from './catalogThunks'
4

    
5
export interface CatalogFilter {
6
    name?: string
7
    type?: string
8
    country?: string
9
}
10

    
11
export interface CatalogState {
12
    items: CatalogItemDto[] // list of all fetched items
13
    filter: CatalogFilter // filter object
14
    filterOpen: boolean
15
    loading: boolean // whether the catalog is loading
16
    error?: string
17
    rowsPerPage: number
18
    rowsPerPageOptions: any[]
19
}
20

    
21
export const ShowAllItemsOption = 'All'
22

    
23
const initialState: CatalogState = {
24
    items: [],
25
    filter: {},
26
    filterOpen: false,
27
    loading: true,
28
    error: undefined,
29
    rowsPerPage: 20,
30
    rowsPerPageOptions: [5, 10, 20, 50, 100, 1000, ShowAllItemsOption],
31
}
32

    
33
const catalogSlice = createSlice({
34
    name: 'catalog',
35
    initialState,
36
    reducers: {
37
        setFilter: (state, action) => ({
38
            ...state,
39
            filter: { ...action.payload },
40
        }),
41
        clearFilter: (state, action) => ({
42
            ...state,
43
            loading: true,
44
            filter: {},
45
        }),
46
        setFilterOpen: (state, action) => ({
47
            ...state,
48
            filterOpen: action.payload,
49
        }),
50
        clear: (state) => ({ ...initialState }),
51
        setLoading: (state) => ({ ...state, loading: true }),
52
        consumeError: (state) => ({ ...state, error: undefined }),
53
        setRowsPerPage: (state, action) => ({
54
            ...state,
55
            rowsPerPage: action.payload,
56
        }),
57
    },
58
    extraReducers: (builder) => {
59
        builder.addCase(fetchItems.pending, (state) => ({
60
            ...state,
61
            loading: true,
62
        }))
63
        builder.addCase(fetchItems.fulfilled, (state, action) => ({
64
            ...state,
65
            items: action.payload,
66
            loading: false,
67
        }))
68
        builder.addCase(fetchItems.rejected, (state, action) => ({
69
            ...state,
70
            loading: false,
71
            error: action.error.message as string,
72
        }))
73
    },
74
})
75

    
76
export const {
77
    setFilter,
78
    clearFilter,
79
    setFilterOpen,
80
    clear,
81
    setLoading,
82
    consumeError,
83
    setRowsPerPage,
84
} = catalogSlice.actions
85
const reducer = catalogSlice.reducer
86
export default reducer
(6-6/7)