This repository was archived by the owner on Apr 18, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 23
/
Copy pathqueries.ts
61 lines (51 loc) · 1.95 KB
/
queries.ts
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
import { useMutation, useQueryClient } from 'react-query'
import { ForumAPI, ItemId, PostContent, CommentContent, VoteValue, ItemKind } from './forum'
export const recentPostQueryKeys = {
recentPosts: ['posts', 'recent'] as const,
recentPostsWithOptions: (opts: {
limit?: number,
includeScore?: boolean }) =>
[...recentPostQueryKeys.recentPosts, opts] as const,
}
export const itemQueryKeys = {
itemDetail: (itemId: ItemId, opts: { includeScore?: boolean } = { }) =>
['items', 'details', itemId.toString(), opts] as const,
}
export function useAddPost() {
const queryClient = useQueryClient()
const executor = ({api, postContent}: {api: ForumAPI, postContent: Omit<PostContent, 'itemKind'>}) =>
api.addPost({...postContent, itemKind: 'POST'})
return useMutation(executor, {
onSuccess: () => {
queryClient.invalidateQueries(recentPostQueryKeys.recentPosts)
}
})
}
export function useAddComment() {
const queryClient = useQueryClient()
const fn = ({api, commentContent}: {api: ForumAPI, commentContent: Omit<CommentContent, 'itemKind'>}) =>
api.addComment({...commentContent, itemKind: 'COMMENT'})
return useMutation(fn, {
onSuccess: (_data, { commentContent }) => {
// invalidate the parent object
queryClient.invalidateQueries(
itemQueryKeys.itemDetail(commentContent.parentId))
},
onError: (error) => {
console.error('error posting comment', error)
}
})
}
export type VoteForItemOpts = {
api: ForumAPI,
itemId: ItemId,
vote: VoteValue,
}
export function useVoteForItem() {
const queryClient = useQueryClient()
return useMutation(({api, itemId, vote}: VoteForItemOpts) => api.voteForItem(itemId, vote), {
onSuccess: (_data, { itemId }) => {
queryClient.invalidateQueries(itemQueryKeys.itemDetail(itemId, { includeScore: true }))
}
})
}