61 lines
1.7 KiB
TypeScript
61 lines
1.7 KiB
TypeScript
import type { AdminAccountDetail } from '@gruperly/shared'
|
|
import { useQuery } from '@tanstack/react-query'
|
|
import type { ReactNode } from 'react'
|
|
import { createContext, useContext } from 'react'
|
|
import { ApiError, getAdminAccount } from '../../lib/api'
|
|
import { errorMessage as apiErrorMessage } from '../../i18n'
|
|
import { i18n } from '../../i18n/instance'
|
|
|
|
type AdminAccountDetailContextValue = {
|
|
account: AdminAccountDetail | null
|
|
isPending: boolean
|
|
isError: boolean
|
|
isNotFound: boolean
|
|
errorMessage: string | null
|
|
retry: () => void
|
|
}
|
|
|
|
const AdminAccountDetailContext = createContext<AdminAccountDetailContextValue | null>(null)
|
|
|
|
export function AdminAccountDetailProvider({
|
|
accountId,
|
|
children,
|
|
}: {
|
|
accountId: string
|
|
children: ReactNode
|
|
}) {
|
|
const accountQuery = useQuery({
|
|
queryKey: ['admin', 'accounts', 'detail', accountId],
|
|
queryFn: () => getAdminAccount(accountId),
|
|
})
|
|
|
|
const error = accountQuery.error
|
|
const isNotFound = error instanceof ApiError && error.status === 404
|
|
const errorMessage = accountQuery.isError
|
|
? apiErrorMessage(error, i18n.t('admin:detail.loadError'))
|
|
: null
|
|
|
|
return (
|
|
<AdminAccountDetailContext.Provider
|
|
value={{
|
|
account: accountQuery.data ?? null,
|
|
isPending: accountQuery.isPending,
|
|
isError: accountQuery.isError,
|
|
isNotFound,
|
|
errorMessage,
|
|
retry: () => void accountQuery.refetch(),
|
|
}}
|
|
>
|
|
{children}
|
|
</AdminAccountDetailContext.Provider>
|
|
)
|
|
}
|
|
|
|
export function useAdminAccountDetail() {
|
|
const context = useContext(AdminAccountDetailContext)
|
|
if (!context) {
|
|
throw new Error('useAdminAccountDetail debe usarse dentro de <AdminAccountDetailProvider>')
|
|
}
|
|
return context
|
|
}
|