-
Notifications
You must be signed in to change notification settings - Fork 2.6k
/
create-discussion.ts
46 lines (37 loc) · 1.19 KB
/
create-discussion.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
import { useMutation, useQueryClient } from '@tanstack/react-query';
import { z } from 'zod';
import { api } from '@/lib/api-client';
import { MutationConfig } from '@/lib/react-query';
import { Discussion } from '@/types/api';
import { getDiscussionsQueryOptions } from './get-discussions';
export const createDiscussionInputSchema = z.object({
title: z.string().min(1, 'Required'),
body: z.string().min(1, 'Required'),
});
export type CreateDiscussionInput = z.infer<typeof createDiscussionInputSchema>;
export const createDiscussion = ({
data,
}: {
data: CreateDiscussionInput;
}): Promise<Discussion> => {
return api.post(`/discussions`, data);
};
type UseCreateDiscussionOptions = {
mutationConfig?: MutationConfig<typeof createDiscussion>;
};
export const useCreateDiscussion = ({
mutationConfig,
}: UseCreateDiscussionOptions = {}) => {
const queryClient = useQueryClient();
const { onSuccess, ...restConfig } = mutationConfig || {};
return useMutation({
onSuccess: (...args) => {
queryClient.invalidateQueries({
queryKey: getDiscussionsQueryOptions().queryKey,
});
onSuccess?.(...args);
},
...restConfig,
mutationFn: createDiscussion,
});
};