-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpostContentSlice.js
64 lines (56 loc) · 1.89 KB
/
postContentSlice.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
import { createAsyncThunk, createSlice } from "@reduxjs/toolkit";
import { fetchPostComments } from "../../redditAPI";
export const fetchPostCommentData = createAsyncThunk(
"postContent/fetchPostCommentsStatus",
async ({ commentsPath, postId }) => {
const postData = await fetchPostComments(commentsPath);
const commentsData = postData[1].data.children;
const comments = [];
commentsData.forEach(obj => {
if (obj.kind === "t1") {
const comment = obj.data;
if (comment.body !== "[removed]") {
comments.push({
author: comment.author,
body: comment.body,
id: comment.id,
score: comment.score,
scoreHidden: comment.score_hidden,
});
}
}
});
return { comments, postId };
}
);
export const initialState = { posts: {} };
export const postContent = createSlice({
name: "postContent",
initialState,
reducers: {
addPost(state, action) {
const { id } = action.payload;
state.posts[id] = action.payload;
},
},
extraReducers: builder => {
builder
.addCase(fetchPostCommentData.pending, (state, action) => {
const { postId } = action.meta.arg;
state.posts[postId].commentsStatus = "pending";
})
.addCase(fetchPostCommentData.fulfilled, (state, action) => {
const { comments, postId } = action.payload;
state.posts[postId].comments = comments;
state.posts[postId].commentsStatus = "fulfilled";
})
.addCase(fetchPostCommentData.rejected, (state, action) => {
const { postId } = action.meta.arg;
state.posts[postId].commentsStatus = "rejected";
})
},
});
export const { addPost } = postContent.actions;
export const selectAllPosts = (state) => state.postContent.posts;
export const selectPost = (state, id) => state.postContent.posts[id];
export default postContent.reducer;