| 89 | }; |
| 90 | |
| 91 | const useBookmarkPost = ({ |
| 92 | onMutate, |
| 93 | mutationKey, |
| 94 | }: UseBookmarkPostProps = {}): UseBookmarkPost => { |
| 95 | const { requestMethod } = useRequestProtocol(); |
| 96 | const client = useQueryClient(); |
| 97 | const { displayToast } = useToastNotification(); |
| 98 | const { user, showLogin } = useContext(AuthContext); |
| 99 | const { logEvent } = useLogContext(); |
| 100 | const { completeAction } = useActions(); |
| 101 | const { openModal } = useLazyModal(); |
| 102 | const postLogEvent = usePostLogEvent(); |
| 103 | const { logOpts } = useActiveFeedContext(); |
| 104 | |
| 105 | const defaultOnMutate: NonNullable<UseBookmarkPostProps['onMutate']> = ({ |
| 106 | id, |
| 107 | }) => { |
| 108 | if (!id) { |
| 109 | return undefined; |
| 110 | } |
| 111 | |
| 112 | const previousPost = client.getQueryData<PostData>( |
| 113 | getPostByIdKey(id), |
| 114 | )?.post; |
| 115 | |
| 116 | updatePostCache(client, id, (post) => ({ |
| 117 | bookmarked: !post.bookmarked, |
| 118 | analytics: post.analytics |
| 119 | ? { |
| 120 | ...post.analytics, |
| 121 | bookmarks: getOptimisticBookmarkCount( |
| 122 | post.analytics.bookmarks, |
| 123 | post.bookmarked, |
| 124 | ), |
| 125 | } |
| 126 | : post.analytics, |
| 127 | })); |
| 128 | |
| 129 | return () => { |
| 130 | if (!previousPost) { |
| 131 | return; |
| 132 | } |
| 133 | |
| 134 | updatePostCache(client, id, () => ({ |
| 135 | bookmarked: previousPost.bookmarked, |
| 136 | bookmark: previousPost.bookmark, |
| 137 | analytics: previousPost.analytics, |
| 138 | })); |
| 139 | }; |
| 140 | }; |
| 141 | |
| 142 | const { mutateAsync: bookmarkPost } = useMutation({ |
| 143 | mutationKey: mutationKey |
| 144 | ? [...bookmarkMutationKey, ...mutationKey] |
| 145 | : bookmarkMutationKey, |
| 146 | mutationFn: ({ mutation, payload }: UseBookmarkPostMutationProps) => { |
| 147 | if (!mutation) { |
| 148 | return Promise.reject(new Error('Missing bookmark mutation')); |