Skip to content

Commit

Permalink
use params required
Browse files Browse the repository at this point in the history
  • Loading branch information
SKairinos committed Aug 15, 2024
1 parent f04cf95 commit 3e685bf
Showing 1 changed file with 46 additions and 10 deletions.
56 changes: 46 additions & 10 deletions src/hooks/router.ts → src/hooks/router.tsx
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { useEffect, type ReactNode } from "react"
import {
useLocation as _useLocation,
useNavigate as _useNavigate,
Expand All @@ -20,18 +21,21 @@ import {
type TryValidateSyncRT,
} from "../utils/schema"

export type Navigate<State extends Record<string, any> = Record<string, any>> =
{
(
to: To,
options?: Omit<NavigateOptions, "state"> & {
state?: State & Partial<PageState>
next?: boolean
},
): void
(delta: number): void
}

export function useNavigate<
State extends Record<string, any> = Record<string, any>,
>(): {
(
to: To,
options?: Omit<NavigateOptions, "state"> & {
state?: State & Partial<PageState>
next?: boolean
},
): void
(delta: number): void
} {
>(): Navigate<State> {
const navigate = _useNavigate()
const searchParams = useSearchParams()

Expand Down Expand Up @@ -120,3 +124,35 @@ export function useParams<

return tryValidateSync(params, objectSchema(shape), validateOptions)
}

export function useParamsRequired<
OnErrorRT extends TryValidateSyncOnErrorRT<ObjectSchemaFromShape<Shape>>,
Shape extends ObjectShape = {},
State extends Record<string, any> = Record<string, any>,
>({
shape,
children,
onValidationError,
validateOptions,
}: {
shape: Shape
children: (
data: NonNullable<
TryValidateSyncRT<ObjectSchemaFromShape<Shape>, OnErrorRT>
>,
) => ReactNode
onValidationError: (navigate: Navigate<State>) => void
validateOptions?: TryValidateSyncOptions<
ObjectSchemaFromShape<Shape>,
OnErrorRT
>
}) {
const params = useParams(shape, validateOptions)
const navigate = useNavigate<State>()

useEffect(() => {
if (!params) onValidationError(navigate)
}, [params, onValidationError, navigate])

return params ? children(params) : <></>
}

0 comments on commit 3e685bf

Please sign in to comment.