Projekt

Obecné

Profil

Stáhnout (1.74 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
    loading: boolean // whether the catalog is loading
15
    error?: string
16
}
17

    
18
const initialState: CatalogState = {
19
    items: [],
20
    filter: {},
21
    loading: true,
22
    error: undefined,
23
}
24

    
25
const catalogSlice = createSlice({
26
    name: 'catalog',
27
    initialState,
28
    reducers: {
29
        setCatalogFilter: (state, action) => ({
30
            ...state,
31
            catalogFilter: action.payload.catalogFilter,
32
        }),
33
        clearFilter: (state, action) => ({
34
            ...state,
35
            loading: true,
36
            catalogFilter: {},
37
        }),
38
        clear: (state) => ({ ...initialState }),
39
        setLoading: (state) => ({ ...state, loading: true }),
40
        consumeError: (state) => ({ ...state, error: undefined }),
41
    },
42
    extraReducers: (builder) => {
43
        builder.addCase(fetchItems.pending, (state) => ({
44
            ...state,
45
            loading: true,
46
        }))
47
        builder.addCase(fetchItems.fulfilled, (state, action) => ({
48
            ...state,
49
            items: action.payload,
50
            loading: false,
51
        }))
52
        builder.addCase(fetchItems.rejected, (state, action) => ({
53
            ...state,
54
            loading: false,
55
            error: action.payload as string,
56
        }))
57
    },
58
})
59

    
60
export const { setCatalogFilter, clearFilter, clear, setLoading, consumeError } = catalogSlice.actions
61
const reducer = catalogSlice.reducer
62
export default reducer
(4-4/5)