-
Notifications
You must be signed in to change notification settings - Fork 0
/
update-community-channel.ts
54 lines (46 loc) · 1.69 KB
/
update-community-channel.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
import { useMutation, useQueryClient } from "@tanstack/react-query";
import { ChatQueries, useChannelsQuery } from "../queries";
import { Channel, useNostrPublishMutation } from "../nostr";
import { useFindHealthyRelayQuery } from "../nostr/mutations/find-healthy-relay";
import { useContext } from "react";
import { Kind } from "nostr-tools";
import { ChatContext } from "../chat-context-provider";
export function useUpdateCommunityChannel(channel?: Channel) {
const queryClient = useQueryClient();
const { data: channels } = useChannelsQuery();
const { activeUsername } = useContext(ChatContext);
const { mutateAsync: updateChannel } = useNostrPublishMutation(
["chats/nostr-update-channel", channel?.communityName],
Kind.ChannelMetadata,
() => {},
);
const { mutateAsync: findHealthyRelay } = useFindHealthyRelayQuery();
return useMutation({
mutationKey: ["chats/update-community-channel", channel?.communityName],
mutationFn: async (newUpdatedChannel: Channel) => {
if (!channel) {
return;
}
const relay = await findHealthyRelay(channel.id);
await updateChannel({
tags: [["e", channel.id, ...(relay ? [relay] : [])]],
eventMetadata: JSON.stringify(newUpdatedChannel),
});
return newUpdatedChannel;
},
onSuccess: (updatedChannel) => {
if (!updatedChannel) {
return;
}
const tempChannels = [...(channels ?? [])];
const index = tempChannels.findIndex(
(ch) => ch.id === updatedChannel?.id,
);
tempChannels[index] = updatedChannel;
queryClient.setQueryData(
[ChatQueries.JOINED_CHANNELS, activeUsername],
tempChannels,
);
},
});
}