feat: enable server side route matching

This commit is contained in:
Valerio Ageno
2024-05-14 21:23:32 +02:00
parent 1ef1a852fc
commit da75dc4a07
4 changed files with 26 additions and 8 deletions
+9 -1
View File
@@ -39,7 +39,15 @@ async fn main() {
async fn catch_all(uri: Uri) -> Html<String> {
dbg!(&uri.path());
let result = SSR.with(|ssr| ssr.borrow_mut().render_to_string(Some(&uri.path())));
let path = &uri.path();
let payload = format!(
r#"{{
"path": "{path}"
}}"#
);
let result = SSR.with(|ssr| ssr.borrow_mut().render_to_string(Some(&payload)));
match result {
Ok(html) => Html(html),
@@ -4,15 +4,19 @@ import { useRouterStore } from '../hooks/useRouterStore'
import { RouteMatch } from './RouteMatch'
import NotFound from './NotFound'
export const Matches = React.memo(function () {
interface MatchesProps {
serverPath?: string
}
export function Matches({ serverPath }: MatchesProps): JSX.Element {
const location = useRouterStore((st) => st.location)
const router = useRouter()
const route = router.routesById[location?.pathname || '']
const route = router.routesById[location?.pathname || serverPath || '']
if (!route) {
return <NotFound />
}
return <RouteMatch route={route} />
})
}
@@ -40,10 +40,14 @@ function RouterContextProvider({
interface RouterProviderProps {
router: Router
serverProps: {
path?: string
}
}
const initRouterStore = (): void => {
const updateLocation = useRouterStore((st) => st.updateLocation)
useLayoutEffect(() => {
const { pathname, hash, href, search } = window.location
updateLocation({
@@ -58,12 +62,14 @@ const initRouterStore = (): void => {
export function RouterProvider({
router,
serverProps,
...rest
}: RouterProviderProps): JSX.Element {
initRouterStore()
return (
<RouterContextProvider router={router} {...rest}>
<Matches />
<Matches serverPath={serverProps.path} />
</RouterContextProvider>
)
}
@@ -4,7 +4,7 @@ import { create } from 'zustand'
export interface ParsedLocation {
href: string
pathname: string
search: URLSearchParams
search?: URLSearchParams
searchStr: string
hash: string
}
@@ -27,8 +27,8 @@ export const useRouterStore = create<RouterState>()((set) => ({
status: 'idle',
location: {
href: '',
pathname: '/',
search: {},
pathname: '',
search: undefined,
searchStr: '',
hash: '',
},