erp-platform/ui/src/routes/dynamicRoutesContext.tsx

60 lines
1.7 KiB
TypeScript
Raw Normal View History

2025-08-12 09:39:09 +00:00
import { RouteDto } from '@/proxy/routes/models'
2025-06-28 21:34:28 +00:00
import React, { createContext, useContext, useEffect, useState } from 'react'
2025-08-11 06:34:44 +00:00
import { useStoreState } from '@/store/store'
2025-06-28 21:34:28 +00:00
interface DynamicRoutesContextProps {
routes: RouteDto[]
loading: boolean
error: string | null
reload: () => void
}
const DynamicRoutesContext = createContext<DynamicRoutesContextProps | undefined>(undefined)
export const useDynamicRoutes = () => {
const ctx = useContext(DynamicRoutesContext)
if (!ctx) throw new Error('useDynamicRoutes must be used within DynamicRoutesProvider')
return ctx
}
export const DynamicRoutesProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => {
2025-08-11 06:34:44 +00:00
const extraProperties = useStoreState((state) => state.abpConfig?.config?.extraProperties)
2025-06-28 21:34:28 +00:00
const [routes, setRoutes] = useState<RouteDto[]>([])
const [loading, setLoading] = useState(true)
const [error, setError] = useState<string | null>(null)
2025-08-11 06:34:44 +00:00
const loadRoutesFromConfig = () => {
2025-06-28 21:34:28 +00:00
setLoading(true)
setError(null)
try {
2025-08-11 06:34:44 +00:00
// Get routes from extraProperties instead of API call
const configRoutes = extraProperties?.routes as RouteDto[]
2025-08-12 09:39:09 +00:00
2025-08-11 06:34:44 +00:00
if (configRoutes && Array.isArray(configRoutes)) {
setRoutes(configRoutes)
2025-06-28 21:34:28 +00:00
} else {
2025-08-11 06:34:44 +00:00
setRoutes([])
setError('No routes found in configuration')
2025-06-28 21:34:28 +00:00
}
} catch (e: any) {
2025-08-11 06:34:44 +00:00
setError(e.message || 'Error loading routes from configuration')
setRoutes([])
2025-06-28 21:34:28 +00:00
} finally {
setLoading(false)
}
}
useEffect(() => {
2025-08-11 06:34:44 +00:00
if (extraProperties) {
loadRoutesFromConfig()
}
}, [extraProperties])
2025-06-28 21:34:28 +00:00
return (
2025-08-11 06:34:44 +00:00
<DynamicRoutesContext.Provider value={{ routes, loading, error, reload: loadRoutesFromConfig }}>
2025-06-28 21:34:28 +00:00
{children}
</DynamicRoutesContext.Provider>
)
}