Skip to content

Commit

Permalink
feat: Allow passing transition options
Browse files Browse the repository at this point in the history
Closes #209, #209.
  • Loading branch information
franky47 committed Jan 27, 2022
1 parent d0e9385 commit 69ed7ed
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 3 deletions.
16 changes: 16 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -144,6 +144,22 @@ const MultipleQueriesDemo = () => {

_Note: support to synchronously update multiple related queries at the same time will come in a future update. See #277._

## Transition Options

By default Next.js will scroll to the top of the page when changing things in the URL.

To prevent this, `router.push()` and `router.replace()` have a third optional
parameter to control transitions, which can be passed on the state setter here:

```ts
const [name, setName] = useQueryState('name')

setName('Foo', {
scroll: false,
shallow: true // Don't run getStaticProps / getServerSideProps / getInitialProps
})
```

## Caveats

Because the Next.js router is not available in an SSR context, this
Expand Down
18 changes: 15 additions & 3 deletions src/useQueryState.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import type { Router } from 'next/router'
import { useRouter } from 'next/router'
import React from 'react'
import { HistoryOptions, Serializers } from './defs'
Expand All @@ -10,9 +11,16 @@ export interface UseQueryStateOptions<T> extends Serializers<T> {
defaultValue: T
}

// Next.js does not export the TransitionsOption interface,
// but we can get it from where it's used:
type TransitionOptions = Parameters<Router['push']>[2]

export type UseQueryStateReturn<T> = [
T,
(value: React.SetStateAction<T>) => Promise<boolean>
(
value: React.SetStateAction<T>,
transitionOptions?: TransitionOptions
) => Promise<boolean>
]

export type UseQueryStateOptionsWithDefault<T> = Pick<
Expand Down Expand Up @@ -126,7 +134,10 @@ export function useQueryState<T = string>(
const value = React.useMemo(getValue, [router.query[key]])

const update = React.useCallback(
(stateUpdater: React.SetStateAction<T | null>) => {
(
stateUpdater: React.SetStateAction<T | null>,
transitionOptions?: TransitionOptions
) => {
const isUpdaterFunction = (
input: any
): input is (prevState: T | null) => T | null => {
Expand Down Expand Up @@ -166,7 +177,8 @@ export function useQueryState<T = string>(
pathname: asPath,
hash,
search
}
},
transitionOptions
)
},
[key, updateUrl]
Expand Down

0 comments on commit 69ed7ed

Please sign in to comment.