expo-duooomi-app/hooks/data/use-templates.ts

107 lines
2.9 KiB
TypeScript

import { root } from '@repo/core'
import { type ListTemplatesInput, type ListTemplatesResult, TemplateController } from '@repo/sdk'
import { useCallback, useRef, useState } from 'react'
import { type ApiError } from '@/lib/types'
import { handleError } from './use-error'
const OWNER_ID = process.env.EXPO_PUBLIC_OWNER_ID || ''
export const useTemplates = () => {
const [loading, setLoading] = useState(false)
const [loadingMore, setLoadingMore] = useState(false)
const [error, setError] = useState<ApiError | null>(null)
const [data, setData] = useState<ListTemplatesResult | undefined>()
const currentPageRef = useRef(1)
const hasMoreRef = useRef(true)
const execute = useCallback(async (params?: ListTemplatesInput) => {
setLoading(true)
setError(null)
currentPageRef.current = params?.page || 1
const template = root.get(TemplateController)
const { data, error } = await handleError(
async () =>
await template.list({
page: params?.page || 1,
limit: params?.limit || 20,
sortBy: params?.sortBy || 'createdAt',
sortOrder: params?.sortOrder || 'desc',
...params,
ownerId: OWNER_ID,
}),
)
if (error) {
setError(error)
setLoading(false)
return { data: undefined, error }
}
const templates = data?.templates || []
hasMoreRef.current = templates.length >= (params?.limit || 20)
setData(data)
setLoading(false)
return { data, error: null }
}, [])
const loadMore = useCallback(
async (params?: Omit<ListTemplatesInput, 'page'>) => {
if (loadingMore || loading || !hasMoreRef.current) return { data: undefined, error: null }
setLoadingMore(true)
const nextPage = currentPageRef.current + 1
const template = root.get(TemplateController)
const { data: newData, error } = await handleError(
async () =>
await template.list({
page: nextPage,
limit: params?.limit || 20,
sortBy: params?.sortBy || 'createdAt',
sortOrder: params?.sortOrder || 'desc',
...params,
ownerId: OWNER_ID,
}),
)
if (error) {
setLoadingMore(false)
return { data: undefined, error }
}
const newTemplates = newData?.templates || []
hasMoreRef.current = newTemplates.length >= (params?.limit || 20)
currentPageRef.current = nextPage
setData((prev) => ({
...newData,
templates: [...(prev?.templates || []), ...newTemplates],
}))
setLoadingMore(false)
return { data: newData, error: null }
},
[loading, loadingMore],
)
const refetch = useCallback(
(params?: ListTemplatesInput) => {
hasMoreRef.current = true
return execute(params)
},
[execute],
)
return {
data,
loading,
loadingMore,
error,
execute,
refetch,
loadMore,
hasMore: hasMoreRef.current,
}
}