-
Notifications
You must be signed in to change notification settings - Fork 1.3k
Expand file tree
/
Copy pathappSlice.ts
More file actions
114 lines (105 loc) · 2.52 KB
/
appSlice.ts
File metadata and controls
114 lines (105 loc) · 2.52 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
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
107
108
109
110
111
112
113
114
import { createSlice, PayloadAction } from '@reduxjs/toolkit';
import { User } from '../types/User';
import { Post } from '../types/Post';
import { Comment } from '../types/Comment';
export interface AppState {
users: User[];
author: number | null;
posts: {
loaded: boolean;
hasError: boolean;
items: Post[];
};
selectedPost: number | null;
comments: {
loaded: boolean;
hasError: boolean;
items: Comment[];
};
}
const initialState: AppState = {
users: [],
author: null,
posts: {
loaded: false,
hasError: false,
items: [],
},
selectedPost: null,
comments: {
loaded: false,
hasError: false,
items: [],
},
};
const appSlice = createSlice({
name: 'app',
initialState,
reducers: {
setUsers(state, action: PayloadAction<User[]>) {
state.users = action.payload;
},
setAuthor(state, action: PayloadAction<number>) {
state.author = action.payload;
},
setPosts(state, action: PayloadAction<Post[]>) {
state.posts.hasError = false;
state.posts.loaded = true;
state.posts.items = action.payload;
},
setSelectedPost(state, action: PayloadAction<number>) {
state.selectedPost = action.payload;
},
clearAuthor(state) {
state.author = null;
},
setPostsLoading(state) {
state.posts.loaded = false;
state.posts.hasError = false;
},
setPostsError(state) {
state.posts.hasError = true;
state.posts.loaded = true;
},
clearSelectedPost(state) {
state.selectedPost = null;
},
setCommentsLoading(state) {
state.comments.loaded = false;
state.comments.hasError = false;
},
setComments(state, action: PayloadAction<Comment[]>) {
state.comments.hasError = false;
state.comments.loaded = true;
state.comments.items = action.payload;
},
setCommentsError(state) {
state.comments.hasError = true;
state.comments.loaded = true;
},
addComment(state, action: PayloadAction<Comment>) {
state.comments.items.push(action.payload);
},
removeComment(state, action: PayloadAction<number>) {
state.comments.items = state.comments.items.filter(
comment => comment.id !== action.payload,
);
},
},
});
export const {
setUsers,
setAuthor,
setPosts,
setSelectedPost,
clearAuthor,
setPostsLoading,
setPostsError,
clearSelectedPost,
setCommentsLoading,
setComments,
setCommentsError,
addComment,
removeComment,
} = appSlice.actions;
export default appSlice.reducer;