Hey is a decentralized and permissionless social media app built with Lens Protocol 馃尶
1import { useApolloClient } from "@apollo/client";
2import { useEditPostMutation, usePostLazyQuery } from "@hey/indexer";
3import type { ApolloClientError } from "@hey/types/errors";
4import { useCallback } from "react";
5import { toast } from "sonner";
6import { usePostStore } from "@/store/non-persisted/post/usePostStore";
7import useTransactionLifecycle from "./useTransactionLifecycle";
8import useWaitForTransactionToComplete from "./useWaitForTransactionToComplete";
9
10interface EditPostProps {
11 onCompleted: () => void;
12 onError: (error: ApolloClientError) => void;
13}
14
15const useEditPost = ({ onCompleted, onError }: EditPostProps) => {
16 const handleTransactionLifecycle = useTransactionLifecycle();
17 const { editingPost, setEditingPost } = usePostStore();
18 const waitForTransactionToComplete = useWaitForTransactionToComplete();
19 const [getPost] = usePostLazyQuery();
20 const { cache } = useApolloClient();
21
22 const updateCache = useCallback(
23 async (toastId: string | number) => {
24 const { data } = await getPost({
25 fetchPolicy: "cache-and-network",
26 variables: { request: { post: editingPost?.id } }
27 });
28
29 if (!data?.post) {
30 return;
31 }
32
33 setEditingPost(undefined);
34 toast.success("Post edited successfully!", { id: toastId });
35 cache.modify({
36 fields: { post: () => data.post },
37 id: cache.identify(data.post)
38 });
39 },
40 [getPost, cache, editingPost]
41 );
42
43 const onCompletedWithTransaction = useCallback(
44 (hash: string) => {
45 const toastId = toast.loading("Editing post...");
46 waitForTransactionToComplete(hash).then(() => updateCache(toastId));
47 return onCompleted();
48 },
49 [waitForTransactionToComplete, updateCache, onCompleted]
50 );
51
52 // Onchain mutations
53 const [editPost] = useEditPostMutation({
54 onCompleted: async ({ editPost }) => {
55 if (editPost.__typename === "PostResponse") {
56 return onCompletedWithTransaction(editPost.hash);
57 }
58
59 return await handleTransactionLifecycle({
60 onCompleted: onCompletedWithTransaction,
61 onError,
62 transactionData: editPost
63 });
64 },
65 onError
66 });
67
68 return { editPost };
69};
70
71export default useEditPost;