Hey is a decentralized and permissionless social media app built with Lens Protocol 馃尶
1import { useApolloClient } from "@apollo/client";
2import { type GroupFragment, useLeaveGroupMutation } from "@hey/indexer";
3import type { ApolloClientError } from "@hey/types/errors";
4import { useCallback, useState } from "react";
5import { toast } from "sonner";
6import { Button } from "@/components/Shared/UI";
7import errorToast from "@/helpers/errorToast";
8import useTransactionLifecycle from "@/hooks/useTransactionLifecycle";
9
10interface LeaveProps {
11 group: GroupFragment;
12 small: boolean;
13}
14
15const Leave = ({ group, small }: LeaveProps) => {
16 const [isSubmitting, setIsSubmitting] = useState(false);
17 const { cache } = useApolloClient();
18 const handleTransactionLifecycle = useTransactionLifecycle();
19
20 const updateCache = () => {
21 if (!group.operations) {
22 return;
23 }
24
25 cache.modify({
26 fields: { isMember: () => false },
27 id: cache.identify(group.operations)
28 });
29 };
30
31 const onCompleted = () => {
32 updateCache();
33 setIsSubmitting(false);
34 toast.success("Left group");
35 };
36
37 const onError = useCallback((error: ApolloClientError) => {
38 setIsSubmitting(false);
39 errorToast(error);
40 }, []);
41
42 const [leaveGroup] = useLeaveGroupMutation({
43 onCompleted: async ({ leaveGroup }) => {
44 if (leaveGroup.__typename === "LeaveGroupResponse") {
45 return onCompleted();
46 }
47
48 if (leaveGroup.__typename === "GroupOperationValidationFailed") {
49 return onError({ message: leaveGroup.reason });
50 }
51
52 return await handleTransactionLifecycle({
53 onCompleted,
54 onError,
55 transactionData: leaveGroup
56 });
57 },
58 onError
59 });
60
61 const handleLeave = async () => {
62 setIsSubmitting(true);
63
64 return await leaveGroup({
65 variables: { request: { group: group.address } }
66 });
67 };
68
69 return (
70 <Button
71 aria-label="Leave"
72 disabled={isSubmitting}
73 loading={isSubmitting}
74 onClick={handleLeave}
75 size={small ? "sm" : "md"}
76 >
77 Leave
78 </Button>
79 );
80};
81
82export default Leave;