mirror of
https://github.com/tuono-labs/tuono
synced 2026-07-25 12:52:47 -07:00
feat: set listener on popstate to allow back and forward browser buttons
This commit is contained in:
@@ -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} />
|
||||
|
||||
Reference in New Issue
Block a user