-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathlistSlice.js
More file actions
63 lines (57 loc) · 1.74 KB
/
listSlice.js
File metadata and controls
63 lines (57 loc) · 1.74 KB
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
import { createAsyncThunk, createSlice } from "@reduxjs/toolkit";
import { listService } from "./listAPI";
const initialState = {
data: [],
activeList: {},
status: 'idle'
}
export const listAsync = createAsyncThunk(
'lists/get',
async () => {
return await listService.list();
}
)
export const saveAsync = createAsyncThunk(
'lists/save',
async (list) => {
return await listService.save(list);
}
)
export const listSlice = createSlice({
name: 'list',
initialState,
reducers: {
activateList(state, action) {
state.activeList = action.payload
}
},
extraReducers: (builder) => {
builder
.addCase(listAsync.fulfilled, (state, action) => {
// all lists loaded
// put lists into state
state.data = action.payload
})
.addCase(saveAsync.fulfilled, (state, action) => {
// list saved
// See if current list exists
const existingListIndex = state.data.findIndex(l => l.id === action.payload.id);
if (existingListIndex > -1) {
// list exists, replace with updated list
state.data[existingListIndex] = action.payload.action;
} else {
// list does not exist, add to end
state.data.push(action.payload);
state.activeList = action.payload;
}
})
}
})
export const selectLists = (state) => {
return state.lists.data;
}
export const selectActiveList = (state) => {
return state.lists.activeList;
}
export default listSlice.reducer;
export const { activateList } = listSlice.actions;