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