Skip to content

Commit

Permalink
feat: added support for NavigateOptions for nextjs app router
Browse files Browse the repository at this point in the history
  • Loading branch information
BowlingX committed Nov 21, 2023
1 parent f94d2e4 commit ae7dc9f
Showing 1 changed file with 23 additions and 8 deletions.
31 changes: 23 additions & 8 deletions src/lib/adapters/nextjs-app-router/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,12 +10,17 @@ import React, { memo, ReactNode, useEffect, useMemo, useRef } from 'react'
import { StoreState } from '../../middleware.js'
import { shallow } from 'zustand/shallow'
import { createSearch } from '../../utils.js'
import { NavigateOptions } from 'next/dist/shared/lib/app-router-context.js'

interface Props {
readonly children?: ReactNode
readonly navigateDefaultOptions?: NavigateOptions
}

const GeschichteForNextAppRouter = ({ children }: Props) => {
const GeschichteForNextAppRouter = ({
children,
navigateDefaultOptions = { scroll: false },
}: Props) => {
const searchParams = useSearchParams()
const { push, replace } = useRouter()
const pathname = usePathname()
Expand All @@ -26,14 +31,20 @@ const GeschichteForNextAppRouter = ({ children }: Props) => {
const { searchParams, push, replace, pathname } = router.current
return {
initialSearch: () => searchParams as unknown as URLSearchParams,
push: async (query) => {
push(`${pathname}${createSearch(query)}`)
push: async (query, options) => {
push(`${pathname}${createSearch(query)}`, {
...navigateDefaultOptions,
...options,
})
},
replace: async (query) => {
replace(`${pathname}${createSearch(query)}`)
replace: async (query, options) => {
replace(`${pathname}${createSearch(query)}`, {
...navigateDefaultOptions,
...options,
})
},
}
}, [])
}, [navigateDefaultOptions])

const useStore = useMemo(
() => createGeschichte(historyInstance),
Expand All @@ -53,10 +64,14 @@ const GeschichteForNextAppRouter = ({ children }: Props) => {
state.updateFromQuery(searchParams as unknown as URLSearchParams)
}
router.current = { push, replace, searchParams, pathname }
}, [push, replace, pathname, searchParams, state])

useEffect(() => {
const { unregister } = state
return () => {
state.unregister()
return unregister()
}
}, [push, replace, pathname, searchParams, state])
}, [state])

return (
<StoreContext.Provider value={useStore}>{children}</StoreContext.Provider>
Expand Down

0 comments on commit ae7dc9f

Please sign in to comment.