personal fork of bluesky app
bsky.kelinci.net
1.5 kB
65 lines
1import type { ChatBskyGroupEditGroup } from '@atcute/bluesky';
2import { ok } from '@atcute/client';
3
4import { useMutation, useQueryClient } from '@tanstack/react-query';
5
6import { getClients } from '#/state/session';
7
8import { logger } from '#/logger';
9
10import { rollbackConvoOptimistic, updateConvoOptimistic } from './utils/convo-cache';
11
12export function useEditGroupChatName(
13 convoId: string | undefined,
14 {
15 onSuccess,
16 onError,
17 }: {
18 onSuccess?: (data: ChatBskyGroupEditGroup.$output) => void;
19 onError?: (error: Error) => void;
20 },
21) {
22 const queryClient = useQueryClient();
23 const { chat } = getClients();
24
25 return useMutation({
26 mutationFn: async ({ name: groupName }: { name: string }) => {
27 if (!convoId) {
28 throw new Error('No convoId provided');
29 }
30 if (!chat) {
31 throw new Error('Not signed in');
32 }
33 const data = await ok(
34 chat.post('chat.bsky.group.editGroup', {
35 input: { convoId, name: groupName },
36 }),
37 );
38 return data;
39 },
40 onMutate: ({ name: groupName }) => {
41 if (!convoId) {
42 return;
43 }
44 return updateConvoOptimistic(queryClient, convoId, (prev) => {
45 if (prev.kind?.$type !== 'chat.bsky.convo.defs#groupConvo') {
46 return undefined;
47 }
48 return {
49 ...prev,
50 kind: { ...prev.kind, name: groupName },
51 };
52 });
53 },
54 onSuccess: (data) => {
55 onSuccess?.(data);
56 },
57 onError: (e, _variables, context) => {
58 logger.error(e);
59 if (convoId && context) {
60 rollbackConvoOptimistic(queryClient, convoId, context);
61 }
62 onError?.(e);
63 },
64 });
65}