|
| 1 | +import { ReactElement } from "react"; |
| 2 | + |
| 3 | +import { Favorite, FavoriteBorder } from "@mui/icons-material"; |
| 4 | +import { IconButton } from "@mui/material"; |
| 5 | + |
| 6 | +import { |
| 7 | + CreateBlogPostReactionCommand, |
| 8 | + DeleteBlogPostReactionRequest, |
| 9 | +} from "src/api"; |
| 10 | +import { blogsApi } from "src/apis"; |
| 11 | +import { |
| 12 | + CacheKeysConstants, |
| 13 | + useMutation, |
| 14 | + useQueryClient, |
| 15 | +} from "src/core/query"; |
| 16 | + |
| 17 | +interface BlogPostLikeButtonProps { |
| 18 | + blogPostId: string; |
| 19 | + reactionId?: string; |
| 20 | +} |
| 21 | + |
| 22 | +export function BlogPostLikeButton({ |
| 23 | + blogPostId, |
| 24 | + reactionId, |
| 25 | +}: BlogPostLikeButtonProps): ReactElement { |
| 26 | + const createMutation = useMutation({ |
| 27 | + mutationFn: ( |
| 28 | + createBlogPostReactionCommand: CreateBlogPostReactionCommand |
| 29 | + ) => blogsApi.createBlogPostReaction({ createBlogPostReactionCommand }), |
| 30 | + }); |
| 31 | + |
| 32 | + const deleteMutation = useMutation({ |
| 33 | + mutationFn: ( |
| 34 | + deleteBlogPostReactionCommand: DeleteBlogPostReactionRequest |
| 35 | + ) => blogsApi.deleteBlogPostReaction(deleteBlogPostReactionCommand), |
| 36 | + }); |
| 37 | + |
| 38 | + const queryClient = useQueryClient(); |
| 39 | + |
| 40 | + async function handleToggleReaction(): Promise<void> { |
| 41 | + if (reactionId) { |
| 42 | + await deleteMutation.mutateAsync( |
| 43 | + { reactionId }, |
| 44 | + { |
| 45 | + onSuccess: () => { |
| 46 | + queryClient.invalidateQueries({ |
| 47 | + queryKey: [CacheKeysConstants.BlogPosts], |
| 48 | + }); |
| 49 | + }, |
| 50 | + } |
| 51 | + ); |
| 52 | + return; |
| 53 | + } |
| 54 | + |
| 55 | + await createMutation.mutateAsync( |
| 56 | + { blogPostId, reaction: ":like" }, |
| 57 | + { |
| 58 | + onSuccess: () => { |
| 59 | + queryClient.invalidateQueries({ |
| 60 | + queryKey: [CacheKeysConstants.BlogPosts], |
| 61 | + }); |
| 62 | + }, |
| 63 | + } |
| 64 | + ); |
| 65 | + } |
| 66 | + |
| 67 | + const isLoading = createMutation.isPending || deleteMutation.isPaused; |
| 68 | + |
| 69 | + return ( |
| 70 | + <IconButton |
| 71 | + aria-label="like" |
| 72 | + color={reactionId ? "primary" : "default"} |
| 73 | + disabled={isLoading} |
| 74 | + onClick={handleToggleReaction} |
| 75 | + > |
| 76 | + {reactionId ? <Favorite /> : <FavoriteBorder />} |
| 77 | + </IconButton> |
| 78 | + ); |
| 79 | +} |
0 commit comments