-
Notifications
You must be signed in to change notification settings - Fork 708
Expand file tree
/
Copy pathpostsSlice.js
More file actions
157 lines (148 loc) · 5.47 KB
/
postsSlice.js
File metadata and controls
157 lines (148 loc) · 5.47 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
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
import {
createSelector,
createEntityAdapter
} from "@reduxjs/toolkit";
import { sub } from 'date-fns';
import { apiSlice } from "../api/apiSlice";
const postsAdapter = createEntityAdapter({
sortComparer: (a, b) => b.date.localeCompare(a.date)
})
const initialState = postsAdapter.getInitialState()
export const extendedApiSlice = apiSlice.injectEndpoints({
endpoints: builder => ({
getPosts: builder.query({
query: () => '/posts',
transformResponse: responseData => {
let min = 1;
const loadedPosts = responseData.map(post => {
if (!post?.date) post.date = sub(new Date(), { minutes: min++ }).toISOString();
if (!post?.reactions) post.reactions = {
thumbsUp: 0,
wow: 0,
heart: 0,
rocket: 0,
coffee: 0
}
return post;
});
return postsAdapter.setAll(initialState, loadedPosts)
},
providesTags: (result, error, arg) => [
{ type: 'Post', id: "LIST" },
...result.ids.map(id => ({ type: 'Post', id }))
]
}),
getPostsByUserId: builder.query({
query: id => `/posts/?userId=${id}`,
transformResponse: responseData => {
let min = 1;
const loadedPosts = responseData.map(post => {
if (!post?.date) post.date = sub(new Date(), { minutes: min++ }).toISOString();
if (!post?.reactions) post.reactions = {
thumbsUp: 0,
wow: 0,
heart: 0,
rocket: 0,
coffee: 0
}
return post;
});
return postsAdapter.setAll(initialState, loadedPosts)
},
providesTags: (result, error, arg) => [
...result.ids.map(id => ({ type: 'Post', id }))
]
}),
addNewPost: builder.mutation({
query: initialPost => ({
url: '/posts',
method: 'POST',
body: {
...initialPost,
userId: Number(initialPost.userId),
date: new Date().toISOString(),
reactions: {
thumbsUp: 0,
wow: 0,
heart: 0,
rocket: 0,
coffee: 0
}
}
}),
invalidatesTags: [
{ type: 'Post', id: "LIST" }
]
}),
updatePost: builder.mutation({
query: initialPost => ({
url: `/posts/${initialPost.id}`,
method: 'PATCH',
body: {
...initialPost,
date: new Date().toISOString()
}
}),
invalidatesTags: (result, error, arg) => [
{ type: 'Post', id: arg.id }
]
}),
deletePost: builder.mutation({
query: ({ id }) => ({
url: `/posts/${id}`,
method: 'DELETE',
body: { id }
}),
invalidatesTags: (result, error, arg) => [
{ type: 'Post', id: arg.id }
]
}),
addReaction: builder.mutation({
query: ({ postId, reactions }) => ({
url: `posts/${postId}`,
method: 'PATCH',
// In a real app, we'd probably need to base this on user ID somehow
// so that a user can't do the same reaction more than once
body: { reactions }
}),
async onQueryStarted({ postId, reactions }, { dispatch, queryFulfilled }) {
// `updateQueryData` requires the endpoint name and cache key arguments,
// so it knows which piece of cache state to update
const patchResult = dispatch(
extendedApiSlice.util.updateQueryData('getPosts', undefined, draft => {
// The `draft` is Immer-wrapped and can be "mutated" like in createSlice
const post = draft.entities[postId]
if (post) post.reactions = reactions
})
)
try {
await queryFulfilled
} catch {
patchResult.undo()
}
}
})
})
})
export const {
useGetPostsQuery,
useGetPostsByUserIdQuery,
useAddNewPostMutation,
useUpdatePostMutation,
useDeletePostMutation,
useAddReactionMutation
} = extendedApiSlice
// returns the query result object
export const selectPostsResult = extendedApiSlice.endpoints.getPosts.select()
// Creates memoized selector
const selectPostsData = createSelector(
selectPostsResult,
postsResult => postsResult.data // normalized state object with ids & entities
)
//getSelectors creates these selectors and we rename them with aliases using destructuring
export const {
selectAll: selectAllPosts,
selectById: selectPostById,
selectIds: selectPostIds
// Pass in a selector that returns the posts slice of state
} = postsAdapter.getSelectors(state => selectPostsData(state) ?? initialState)