feat: initialize router on landing

This commit is contained in:
Valerio Ageno
2024-05-11 16:22:15 +02:00
parent 90de047a07
commit 4e1d0b6252
4 changed files with 24 additions and 32 deletions
@@ -3,29 +3,11 @@ import { useRouter } from '../hooks/useRouter'
import { useRouterStore } from '../hooks/useRouterStore'
import NotFound from './NotFound'
export function Matches(): JSX.Element | undefined {
const matchId = useRouterStore.getState().matches[0]?.id
//if (!matchId) return <></>
return (
<React.Suspense>
<Match id={matchId} />
</React.Suspense>
)
}
interface MatchProps {
id: string
}
const Match = React.memo(function ({ id }: MatchProps) {
export const Matches = React.memo(function () {
const location = useRouterStore((st) => st.location)
const router = useRouter()
console.log(router, location)
const route = router.routesById[location?.pathname]
const route = router.routesById[location?.pathname || '']
if (!route) {
return <NotFound />
@@ -35,5 +17,5 @@ const Match = React.memo(function ({ id }: MatchProps) {
console.log('Has rust handler')
}
return route.component()
return route.options.component()
})
@@ -1,6 +1,7 @@
import * as React from 'react'
import { getRouterContext } from './RouterContext'
import { Matches } from './Matches'
import { useRouterStore } from '../hooks/useRouterStore'
import React, { useLayoutEffect, type ReactNode } from 'react'
type Router = any
@@ -30,28 +31,37 @@ function RouterContextProvider({
<router.options.defaultPendingComponent />
) : null
const provider = (
return (
<React.Suspense fallback={pendingElement}>
<routerContext.Provider value={router}>{children}</routerContext.Provider>
</React.Suspense>
)
// NOTE: verify usefulness
if (router.options.Wrap) {
return <router.options.Wrap>{provider}</router.options.Wrap>
}
return provider
}
interface RouterProviderProps {
router: Router
}
const initRouterStore = (): void => {
const updateLocation = useRouterStore((st) => st.updateLocation)
console.log(window.location)
useLayoutEffect(() => {
const { pathname, hash, href, search } = window.location
updateLocation({
pathname,
hash,
href,
searchStr: search,
search: new URLSearchParams(search),
})
}, [])
}
export function RouterProvider({
router,
...rest
}: RouterProviderProps): JSX.Element {
initRouterStore()
return (
<RouterContextProvider router={router} {...rest}>
<Matches />
@@ -4,7 +4,7 @@ import { create } from 'zustand'
export interface ParsedLocation {
href: string
pathname: string
search: Record<string, string>
search: URLSearchParams
searchStr: string
hash: string
}
+1 -1
View File
@@ -11,7 +11,7 @@ interface CreateRouter {
}
interface RouteOptions {
component?: ReactNode
component?: () => ReactNode
hasHandler?: boolean
routeTree?: RouteTree
}