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

50 lines
1.3 KiB
TypeScript

import { ApiError } from "@/lib/types"
import { useState, useCallback } from "react"
import { OWNER_ID } from "@/hooks/constants"
import { root } from '@repo/core'
import { TemplateController, ListTemplatesInput, ListTemplatesResult } from "@repo/sdk"
import { useError } from "./use-error"
export const useTemplates = () => {
const [loading, setLoading] = useState(false)
const [error, setError] = useState<ApiError | null>(null)
const [data, setData] = useState<ListTemplatesResult | undefined>()
const execute = useCallback(async (params?: ListTemplatesInput) => {
setLoading(true)
setError(null)
const template = root.get(TemplateController)
const { data, error } = await useError(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 }
}
setData(data)
setLoading(false)
return { data, error: null }
}, [])
const refetch = useCallback((params?: ListTemplatesInput) => {
return execute(params)
}, [execute])
return {
data,
loading,
error,
execute,
refetch,
}
}