feat: set zustand store server side

This commit is contained in:
Valerio Ageno
2024-05-15 20:42:16 +02:00
parent da75dc4a07
commit fc1d9013f8
4 changed files with 23 additions and 15 deletions
@@ -1,18 +1,13 @@
import * as React from 'react'
import { useRouter } from '../hooks/useRouter' import { useRouter } from '../hooks/useRouter'
import { useRouterStore } from '../hooks/useRouterStore' import { useRouterStore } from '../hooks/useRouterStore'
import { RouteMatch } from './RouteMatch' import { RouteMatch } from './RouteMatch'
import NotFound from './NotFound' import NotFound from './NotFound'
interface MatchesProps { export function Matches(): JSX.Element {
serverPath?: string
}
export function Matches({ serverPath }: MatchesProps): JSX.Element {
const location = useRouterStore((st) => st.location) const location = useRouterStore((st) => st.location)
const router = useRouter() const router = useRouter()
const route = router.routesById[location?.pathname || serverPath || ''] const route = router.routesById[location.pathname]
if (!route) { if (!route) {
return <NotFound /> return <NotFound />
@@ -40,14 +40,25 @@ function RouterContextProvider({
interface RouterProviderProps { interface RouterProviderProps {
router: Router router: Router
serverProps: { serverProps?: ServerProps
path?: string
}
} }
const initRouterStore = (): void => { interface ServerProps {
path: string
}
const initRouterStore = (props?: ServerProps): void => {
const updateLocation = useRouterStore((st) => st.updateLocation) const updateLocation = useRouterStore((st) => st.updateLocation)
if (typeof window === 'undefined') {
updateLocation({
pathname: props?.path || '',
hash: '',
href: '',
searchStr: '',
})
}
useLayoutEffect(() => { useLayoutEffect(() => {
const { pathname, hash, href, search } = window.location const { pathname, hash, href, search } = window.location
updateLocation({ updateLocation({
@@ -65,11 +76,11 @@ export function RouterProvider({
serverProps, serverProps,
...rest ...rest
}: RouterProviderProps): JSX.Element { }: RouterProviderProps): JSX.Element {
initRouterStore() initRouterStore(serverProps)
return ( return (
<RouterContextProvider router={router} {...rest}> <RouterContextProvider router={router} {...rest}>
<Matches serverPath={serverProps.path} /> <Matches />
</RouterContextProvider> </RouterContextProvider>
) )
} }
@@ -1,4 +1,3 @@
import * as React from 'react'
import { create } from 'zustand' import { create } from 'zustand'
export interface ParsedLocation { export interface ParsedLocation {
@@ -13,7 +12,7 @@ interface RouterState {
isLoading: boolean isLoading: boolean
isTransitioning: boolean isTransitioning: boolean
status: 'idle' status: 'idle'
location?: ParsedLocation location: ParsedLocation
matches: string[] matches: string[]
pendingMatches: string[] pendingMatches: string[]
cachedMatches: string[] cachedMatches: string[]
Executable
+3
View File
@@ -0,0 +1,3 @@
#!/bin/bash
pnpm dev & cargo watch -x build -w crates/