brf/client/admin/components/route.tsx
2025-12-18 07:31:37 +01:00

26 lines
941 B
TypeScript

// @ts-nocheck
import { h } from 'preact'
import { useEffect, useState } from 'preact/hooks'
import { route } from 'preact-router'
import { useCurrentUser } from '../contexts/current_user.ts'
/** @type {import('preact').FunctionComponent<{ auth: boolean, path: string, component: () => any, loadComponent: boolean}} Page */
const Route = ({ auth, path, component, loadComponent = true }) => {
const [Component, setComponent] = useState(null)
const { user } = useCurrentUser()
useEffect(async () => {
if (auth ? !user : user) return route(user ? '/admin' : '/admin/login', true)
const loadedComponent = loadComponent ? (await component()).default : component
// Wrapping in arrow function is required since loadedComponent is a function
// and setComponent will call functions passed to it
setComponent(() => loadedComponent)
}, [user])
return Component && <Component path={path} />
}
export default Route