-
Notifications
You must be signed in to change notification settings - Fork 7
/
itemSlice.js
71 lines (63 loc) · 1.89 KB
/
itemSlice.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
import { createAsyncThunk, createSlice } from "@reduxjs/toolkit";
import { itemService } from "./itemAPI";
const initialState = {
data: [],
status: 'idle'
}
export const listAsync = createAsyncThunk(
'items/getList',
async (data) => {
return await itemService.list(data);
}
)
export const loadAsync = createAsyncThunk(
'items/load',
async (data) => {
return await itemService.load(data);
}
)
export const saveAsync = createAsyncThunk(
'items/save',
async (data) => {
return await itemService.save(data);
}
)
export const removeAsync = createAsyncThunk(
'items/remove',
async (data) => {
return await itemService.delete(data);
}
)
export const itemSlice = createSlice({
name: 'item',
initialState,
reducers: {
},
extraReducers: (builder) => {
builder
.addCase(listAsync.fulfilled, (state, action) => {
// put items into state
state.data = action.payload;
})
.addCase(removeAsync.fulfilled, (state, action) => {
// remove item from state
state.data = state.data.filter(i => i.id !== action.payload.id);
})
.addCase(saveAsync.fulfilled, (state, action) => {
// See if current item exists
const existingItemIndex = state.data.findIndex(i => i.id === action.payload.id);
if (existingItemIndex > -1) {
// item exists, replace with updated item
state.data[existingItemIndex] = action.payload;
}
else {
// item does not exist, add new item to end
state.data.push(action.payload);
}
})
},
})
export const selectListItems = (state) => {
return state.items.data;
}
export default itemSlice.reducer;