-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtodosSlice.js
106 lines (89 loc) · 2.11 KB
/
todosSlice.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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
import { createEntityAdapter, createSlice } from '@reduxjs/toolkit';
export const VISIBILITY_FILTERS = {
SHOW_ALL: 'SHOW_ALL',
SHOW_COMPLETED: 'SHOW_COMPLETED',
SHOW_ACTIVE: 'SHOW_ACTIVE',
};
const todosAdapter = createEntityAdapter();
export const todosSelector = todosAdapter.getSelectors((state) => state.todos);
export const todosSlice = createSlice({
name: 'todos',
initialState: todosAdapter.getInitialState({
visibilityFilter: VISIBILITY_FILTERS.SHOW_ALL,
}),
reducers: {
add: (state, action) => {
const { id, text } = action.payload;
todosAdapter.addOne(state, {
id,
text,
completed: false,
editing: false,
});
},
toggleAll: (state) => {
const allCompleted = state.ids.every(
(id) => state.entities[id].completed
);
const completed = allCompleted ? false : true;
state.ids.forEach((id) => {
state.entities[id].completed = completed;
});
},
toggle: (state, action) => {
const { id } = action.payload;
const todo = state.entities[id];
if (!todo) {
return;
}
todosAdapter.updateOne(state, {
id,
changes: { completed: !todo.completed },
});
},
toggleEdit: (state, action) => {
const { id } = action.payload;
const todo = state.entities[id];
if (!todo) {
return;
}
todosAdapter.updateOne(state, {
id,
changes: { editing: !todo.editing },
});
},
remove: (state, action) => {
todosAdapter.removeOne(state, action.payload.id);
},
save: (state, action) => {
const { id, text } = action.payload;
todosAdapter.updateOne(state, {
id,
changes: {
text,
editing: false,
},
});
},
clearCompleted: (state, action) => {
const completedIds = state.ids.filter(
(id) => state.entities[id].completed
);
todosAdapter.removeMany(state, completedIds);
},
setVisibilityFilter: (state, action) => {
state.visibilityFilter = action.payload;
},
},
});
// Action creators are generated for each case reducer function
export const {
add,
toggleAll,
toggle,
toggleEdit,
remove,
save,
clearCompleted,
} = todosSlice.actions;
export default todosSlice.reducer;