({ post }: { post: Post })
| 22 | import { postLogEvent } from '../lib/feed'; |
| 23 | |
| 24 | const usePoll = ({ post }: { post: Post }) => { |
| 25 | const { user } = useAuthContext(); |
| 26 | const { logEvent } = useLogContext(); |
| 27 | const { queryKey } = useActiveFeedContext(); |
| 28 | const queryClient = useQueryClient(); |
| 29 | const { toggleGroup, getGroupStatus } = useNotificationSettings(); |
| 30 | const { displayToast } = useToastNotification(); |
| 31 | |
| 32 | const { mutate, isPending: isCastingVote } = useMutation({ |
| 33 | mutationFn: (optionId: string) => votePoll({ postId: post.id, optionId }), |
| 34 | onMutate: (optionId: string) => { |
| 35 | const adsQueryKey = queryKey ? [RequestKey.Ads, ...queryKey] : null; |
| 36 | const currentFeedData = |
| 37 | queryClient.getQueryData<InfiniteData<FeedData>>(queryKey); |
| 38 | const currentAdsData = |
| 39 | queryClient.getQueryData<InfiniteData<Ad>>(adsQueryKey); |
| 40 | |
| 41 | const updatedOptions = post.pollOptions.map((option) => { |
| 42 | if (option.id === optionId) { |
| 43 | return { ...option, numVotes: option.numVotes + 1 }; |
| 44 | } |
| 45 | return option; |
| 46 | }); |
| 47 | |
| 48 | const postUpdate = { |
| 49 | numPollVotes: post.numPollVotes + 1, |
| 50 | pollOptions: updatedOptions, |
| 51 | userState: { |
| 52 | ...post.userState, |
| 53 | pollOption: { id: optionId }, |
| 54 | }, |
| 55 | }; |
| 56 | |
| 57 | updatePostCache(queryClient, post.id, postUpdate); |
| 58 | |
| 59 | if (currentFeedData) { |
| 60 | const updateFeed = updateCachedPagePost(queryKey, queryClient); |
| 61 | const feedData = |
| 62 | queryClient.getQueryData<InfiniteData<FeedData>>(queryKey); |
| 63 | |
| 64 | const { pageIndex, index } = findIndexOfPostInData( |
| 65 | feedData, |
| 66 | post.id, |
| 67 | false, |
| 68 | ); |
| 69 | |
| 70 | if (pageIndex > -1 && index > -1) { |
| 71 | const currentPost = getFeedApiItemPost( |
| 72 | feedData.pages[pageIndex].page.edges[index].node, |
| 73 | ); |
| 74 | |
| 75 | if (currentPost) { |
| 76 | updateFeed(pageIndex, index, { |
| 77 | ...currentPost, |
| 78 | ...postUpdate, |
| 79 | }); |
| 80 | } |
| 81 | } |
no test coverage detected