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 { useRouterStore } from '../hooks/useRouterStore'
import { RouteMatch } from './RouteMatch'
import NotFound from './NotFound'
interface MatchesProps {
serverPath?: string
}
export function Matches({ serverPath }: MatchesProps): JSX.Element {
export function Matches(): JSX.Element {
const location = useRouterStore((st) => st.location)
const router = useRouter()
const route = router.routesById[location?.pathname || serverPath || '']
const route = router.routesById[location.pathname]
if (!route) {
return <NotFound />
@@ -40,14 +40,25 @@ function RouterContextProvider({
interface RouterProviderProps {
router: Router
serverProps: {
path?: string
}
serverProps?: ServerProps
}
const initRouterStore = (): void => {
interface ServerProps {
path: string
}
const initRouterStore = (props?: ServerProps): void => {
const updateLocation = useRouterStore((st) => st.updateLocation)
if (typeof window === 'undefined') {
updateLocation({
pathname: props?.path || '',
hash: '',
href: '',
searchStr: '',
})
}
useLayoutEffect(() => {
const { pathname, hash, href, search } = window.location
updateLocation({
@@ -65,11 +76,11 @@ export function RouterProvider({
serverProps,
...rest
}: RouterProviderProps): JSX.Element {
initRouterStore()
initRouterStore(serverProps)
return (
<RouterContextProvider router={router} {...rest}>
<Matches serverPath={serverProps.path} />
<Matches />
</RouterContextProvider>
)
}
@@ -1,4 +1,3 @@
import * as React from 'react'
import { create } from 'zustand'
export interface ParsedLocation {
@@ -13,7 +12,7 @@ interface RouterState {
isLoading: boolean
isTransitioning: boolean
status: 'idle'
location?: ParsedLocation
location: ParsedLocation
matches: string[]
pendingMatches: string[]
cachedMatches: string[]
Executable
+3
View File
@@ -0,0 +1,3 @@
#!/bin/bash
pnpm dev & cargo watch -x build -w crates/