feat: set listener on popstate to allow back and forward browser buttons

This commit is contained in:
Valerio Ageno
2024-06-07 21:01:21 +02:00
parent 753bd21c14
commit 821b38e269
2 changed files with 25 additions and 2 deletions
@@ -8,7 +8,7 @@ export default function Link(
e.preventDefault()
props.onClick?.(e)
useRouterStore.setState({ location: { pathname: props.href || '' } })
window.history.pushState('', '', props.href)
history.pushState(props.href, '', props.href)
}
return (
<a {...props} onClick={handleTransition}>
@@ -1,7 +1,7 @@
import { getRouterContext } from './RouterContext'
import { Matches } from './Matches'
import { useRouterStore } from '../hooks/useRouterStore'
import React, { useLayoutEffect, type ReactNode } from 'react'
import React, { useEffect, useLayoutEffect, type ReactNode } from 'react'
type Router = any
@@ -72,12 +72,35 @@ const initRouterStore = (props?: ServerProps): void => {
}, [])
}
const useListenUrlUpdates = (): void => {
const updateLocation = useRouterStore((st) => st.updateLocation)
const updateLocationOnPopStateChange = ({ target }: any): void => {
const { pathname, hash, href, search } = target.location
updateLocation({
pathname,
hash,
href,
searchStr: search,
search: new URLSearchParams(search),
})
}
useEffect(() => {
window.addEventListener('popstate', updateLocationOnPopStateChange)
return (): void => {
window.removeEventListener('popstate', updateLocationOnPopStateChange)
}
}, [])
}
export function RouterProvider({
router,
serverProps,
}: RouterProviderProps): JSX.Element {
initRouterStore(serverProps)
useListenUrlUpdates()
return (
<RouterContextProvider router={router}>
<Matches serverSideProps={serverProps?.props} />