44 lines
1.9 KiB
TypeScript
44 lines
1.9 KiB
TypeScript
import { useState } from 'react'
|
|
import { useMutation, useQueryClient } from '@tanstack/react-query'
|
|
import { likePostMutation, unlikePostMutation } from '@nalssigak/shared/api/client/@tanstack/react-query.gen'
|
|
import type { PostReaction, ResFeed } from '@nalssigak/shared/api/client/types.gen'
|
|
import { track } from '../lib/analytics'
|
|
|
|
export type PinnedKey = 'hero_post' | 'gak_post' | 'foliage_post' | 'events_post' | 'season_post'
|
|
|
|
/** 히어로·오늘의 각·단풍 지도·띠처럼 포스트 틀이 아닌 카드의 좋아요. 화면을 먼저 바꾸고 실패하면 되돌린다 */
|
|
export function usePinnedLike(key: PinnedKey, r?: PostReaction | null) {
|
|
const queryClient = useQueryClient()
|
|
const like = useMutation(likePostMutation())
|
|
const unlike = useMutation(unlikePostMutation())
|
|
const [failed, setFailed] = useState(false)
|
|
const liked = !!r?.liked
|
|
const count = r?.like_count ?? 0
|
|
const patch = (values: Partial<PostReaction>) =>
|
|
queryClient.setQueriesData<ResFeed>({ predicate: (q) => (q.queryKey[0] as { _id?: string } | undefined)?._id === 'getFeed' }, (feed) =>
|
|
feed?.[key] && feed[key].post_id === r?.post_id ? { ...feed, [key]: { ...feed[key], ...values } } : feed,
|
|
)
|
|
const toggle = () => {
|
|
if (!r || like.isPending || unlike.isPending) return
|
|
const on = !liked
|
|
setFailed(false)
|
|
patch({ liked: on, like_count: count + (on ? 1 : -1) })
|
|
const revert = () => {
|
|
patch({ liked, like_count: count })
|
|
setFailed(true)
|
|
}
|
|
;(on ? like : unlike).mutate(
|
|
{ path: { post_id: r.post_id } },
|
|
{
|
|
onSuccess: (res) => {
|
|
if (!res.result?.success) return revert()
|
|
patch({ liked: res.liked ?? on, ...(res.like_count != null ? { like_count: res.like_count } : {}) })
|
|
if (on) track('like', { content_type: key, item_id: r.post_id })
|
|
},
|
|
onError: revert,
|
|
},
|
|
)
|
|
}
|
|
return { liked, count, failed, toggle }
|
|
}
|