fix: pass initial count to hooks for correct optimistic update
- Add initialLikeCount and initialFavoriteCount parameters - Use item.likeCount/item.favoriteCount as fallback - Fixes issue where count resets to 0 on first click
This commit is contained in:
@@ -6,7 +6,7 @@ import { type ApiError } from '@/lib/types'
|
||||
import { handleError } from './use-error'
|
||||
import { templateSocialStore } from '@/stores/templateSocialStore'
|
||||
|
||||
export const useTemplateLike = (templateId?: string) => {
|
||||
export const useTemplateLike = (templateId?: string, initialLikeCount?: number) => {
|
||||
const [loading, setLoading] = useState<boolean>(false)
|
||||
const [error, setError] = useState<ApiError | null>(null)
|
||||
|
||||
@@ -19,7 +19,7 @@ export const useTemplateLike = (templateId?: string) => {
|
||||
setError(null)
|
||||
|
||||
// 乐观更新:立即更新状态
|
||||
const currentCount = templateSocialStore.getLikeCount(templateId) ?? 0
|
||||
const currentCount = templateSocialStore.getLikeCount(templateId) ?? initialLikeCount ?? 0
|
||||
templateSocialStore.setLiked(templateId, true)
|
||||
templateSocialStore.setLikeCount(templateId, currentCount + 1)
|
||||
|
||||
@@ -44,7 +44,7 @@ export const useTemplateLike = (templateId?: string) => {
|
||||
}
|
||||
|
||||
return {}
|
||||
}, [templateId])
|
||||
}, [templateId, initialLikeCount])
|
||||
|
||||
const unlike = useCallback(async (): Promise<{ error?: ApiError }> => {
|
||||
if (!templateId) {
|
||||
@@ -55,7 +55,7 @@ export const useTemplateLike = (templateId?: string) => {
|
||||
setError(null)
|
||||
|
||||
// 乐观更新:立即更新状态
|
||||
const currentCount = templateSocialStore.getLikeCount(templateId) ?? 0
|
||||
const currentCount = templateSocialStore.getLikeCount(templateId) ?? initialLikeCount ?? 0
|
||||
templateSocialStore.setLiked(templateId, false)
|
||||
templateSocialStore.setLikeCount(templateId, Math.max(0, currentCount - 1))
|
||||
|
||||
@@ -80,7 +80,7 @@ export const useTemplateLike = (templateId?: string) => {
|
||||
}
|
||||
|
||||
return {}
|
||||
}, [templateId])
|
||||
}, [templateId, initialLikeCount])
|
||||
|
||||
const checkLiked = useCallback(async (): Promise<{ error?: ApiError }> => {
|
||||
if (!templateId) {
|
||||
@@ -106,7 +106,7 @@ export const useTemplateLike = (templateId?: string) => {
|
||||
templateSocialStore.setLiked(templateId, data.liked)
|
||||
}
|
||||
return {}
|
||||
}, [templateId])
|
||||
}, [templateId, initialLikeCount])
|
||||
|
||||
return {
|
||||
loading,
|
||||
|
||||
Reference in New Issue
Block a user