expo-duooomi-app/hooks/actions/use-template-interaction.ts

114 lines
3.1 KiB
TypeScript

import { root } from '@repo/core'
import { TemplateSocialController } from '@repo/sdk'
import { useCallback, useState } from 'react'
import { type ApiError } from '@/lib/types'
import { handleError } from '../data/use-error'
export const useTemplateInteraction = () => {
const [loading, setLoading] = useState(false)
const [error, setError] = useState<ApiError | null>(null)
const likeTemplate = useCallback(async (templateId: string) => {
setLoading(true)
setError(null)
const templateSocial = root.get(TemplateSocialController)
const { data, error } = await handleError(async () => await templateSocial.like({ templateId }))
if (error) {
setError(error)
setLoading(false)
return { success: false, error }
}
setLoading(false)
return { success: data?.success || true, error: null }
}, [])
const unlikeTemplate = useCallback(async (templateId: string) => {
setLoading(true)
setError(null)
const templateSocial = root.get(TemplateSocialController)
const { data, error } = await handleError(async () => await templateSocial.unlike({ templateId }))
if (error) {
setError(error)
setLoading(false)
return { success: false, error }
}
setLoading(false)
return { success: data?.success || true, error: null }
}, [])
const checkLiked = useCallback(async (templateId: string) => {
const templateSocial = root.get(TemplateSocialController)
const { data, error } = await handleError(async () => await templateSocial.checkLiked({ templateId }))
if (error) {
return { liked: false, error }
}
return { liked: data?.liked || false, error: null }
}, [])
const favoriteTemplate = useCallback(async (templateId: string) => {
setLoading(true)
setError(null)
const templateSocial = root.get(TemplateSocialController)
const { data, error } = await handleError(async () => await templateSocial.favorite({ templateId }))
if (error) {
setError(error)
setLoading(false)
return { success: false, error }
}
setLoading(false)
return { success: data?.success || true, error: null }
}, [])
const unfavoriteTemplate = useCallback(async (templateId: string) => {
setLoading(true)
setError(null)
const templateSocial = root.get(TemplateSocialController)
const { data, error } = await handleError(async () => await templateSocial.unfavorite({ templateId }))
if (error) {
setError(error)
setLoading(false)
return { success: false, error }
}
setLoading(false)
return { success: data?.success || true, error: null }
}, [])
const checkFavorited = useCallback(async (templateId: string) => {
const templateSocial = root.get(TemplateSocialController)
const { data, error } = await handleError(async () => await templateSocial.checkFavorited({ templateId }))
if (error) {
return { favorited: false, error }
}
return { favorited: data?.favorited || false, error: null }
}, [])
return {
loading,
error,
likeTemplate,
unlikeTemplate,
checkLiked,
favoriteTemplate,
unfavoriteTemplate,
checkFavorited,
}
}