expo-duooomi-app/hooks/data/use-template-generations.ts

107 lines
2.7 KiB
TypeScript

import { root } from '@repo/core'
import { type ListTemplateGenerationsInput, type TemplateGeneration, TemplateGenerationController } from '@repo/sdk'
import { useCallback, useRef, useState } from 'react'
import { type ApiError } from '@/lib/types'
import { handleError } from './use-error'
const pageSize = 12
export const useTemplateGenerations = () => {
const [loading, setLoading] = useState(true)
const [loadingMore, setLoadingMore] = useState(false)
const [error, setError] = useState<ApiError | null>(null)
const [data, setData] = useState<TemplateGeneration[]>([])
const currentPageRef = useRef(1)
const hasMoreRef = useRef(true)
const load = useCallback(async (params?: ListTemplateGenerationsInput) => {
setLoading(true)
setError(null)
currentPageRef.current = 1
const templateGeneration = root.get(TemplateGenerationController)
const { data, error } = await handleError(
async () =>
await templateGeneration.list({
page: currentPageRef.current,
limit: params?.limit || pageSize,
...params,
}),
)
if (error) {
setError(error)
setLoading(false)
return
}
const items = data?.data || []
hasMoreRef.current = items.length >= (params?.limit || pageSize)
const filterData = items?.filter((item) => !!item.id)
setData(filterData)
setLoading(false)
return { data, error: null }
}, [])
const loadMore = useCallback(
async (params?: Omit<ListTemplateGenerationsInput, 'page'>) => {
const hasMore = hasMoreRef.current
if (!hasMore) return
setLoadingMore(true)
const nextPage = currentPageRef.current + 1
const templateGeneration = root.get(TemplateGenerationController)
const { data: newData, error } = await handleError(
async () =>
await templateGeneration.list({
page: nextPage,
limit: params?.limit || pageSize,
...params,
}),
)
if (error) {
setLoadingMore(false)
return { data: undefined, error }
}
const newItems = newData?.data || []
hasMoreRef.current = newItems.length >= (params?.limit || pageSize)
currentPageRef.current = nextPage
const filterData = newItems?.filter((item) => !!item.id)
setData((prev) => [...prev, ...filterData])
setLoadingMore(false)
return { data: newData, error: null }
},
[loading, loadingMore],
)
const refetch = useCallback(
(params?: ListTemplateGenerationsInput) => {
hasMoreRef.current = true
return load(params)
},
[load],
)
return {
data,
loading,
loadingMore,
error,
load,
refetch,
loadMore,
hasMore: hasMoreRef.current,
}
}