Gathering detailed insights and metrics for use-next-query-params
Gathering detailed insights and metrics for use-next-query-params
Gathering detailed insights and metrics for use-next-query-params
Gathering detailed insights and metrics for use-next-query-params
use-next-query-state
A custom React hook designed to synchronize component state with the URL's query parameters. This allows you to easily reflect a component's state in the URL or initialize a component's state from the URL.
next-query-string-navigation
React hook to be used on NextJS components to trigger url based navigation
@next-hooks/use-query-params
Congrats! You just saved yourself hours of work by bootstrapping this project with DTS. Let’s get you oriented with what’s here and how to use it.
A React hook designed for Next.js applications to link client states to query parameters.
npm install use-next-query-params
Typescript
Module System
Node Version
NPM Version
TypeScript (95.73%)
JavaScript (4.21%)
Shell (0.06%)
Total Downloads
0
Last Day
0
Last Week
0
Last Month
0
Last Year
0
MIT License
1 Stars
40 Commits
1 Watchers
2 Branches
1 Contributors
Updated on Apr 11, 2023
Latest Version
1.2.1
Package Id
use-next-query-params@1.2.1
Unpacked Size
232.36 kB
Size
41.59 kB
File Count
81
NPM Version
8.19.2
Node Version
16.18.0
Published on
Apr 13, 2023
Cumulative downloads
Total Downloads
Last Day
0%
NaN
Compared to previous day
Last Week
0%
NaN
Compared to previous week
Last Month
0%
NaN
Compared to previous month
Last Year
0%
NaN
Compared to previous year
1
33
A React hook for linking states to query parameters in Next.js applications. This hook is designed specifically for Next.js, but compatible with other React routers with the adapter design.
Demo application: https://use-next-query-params.vercel.app/
Codesandbox: https://codesandbox.io/p/sandbox/use-next-query-params-demo-qqwbst
Also see app
folder for a demo Next.js application used for Cypress tests.
1# npm 2npm install use-next-query-params 3 4# yarn 5yarn add use-next-query-params 6 7# pnpm 8pnpm add use-next-query-params
In the _app.tsx
(or _app.jsx
) file, wrap your application in NextQueryParamsProvider
:
1// pages/_app.tsx 2import { useRouter } from 'next/router'; 3import { NextQueryParamsProvider, createNextRouterAdapter } from 'use-next-query-params'; 4 5export default function App({ Component, pageProps }) { 6 const router = useRouter(); 7 return ( 8 <NextQueryParamsProvider adapter={createNextRouterAdapter(router)}> 9 // Your application 10 </NextQueryParamsProvider> 11 ); 12}
Then, in your page component, use the useNextQueryParams
hook to link states to URL query
parameters:
1// pages/example.tsx 2import { useState } from 'react'; 3import { 4 createStrQueryParam, 5 createNumQueryParam, 6 useNextQueryParams 7} from 'use-next-query-params'; 8 9export default function ExamplePage() { 10 const [counter, setCounter] = useState(0); 11 const [displayName, setDisplayName] = useState(''); 12 // result example: http://localhost:3000/example?count=0&name=John+Doe 13 useNextQueryParams({ 14 count: createNumQueryParam({ 15 value: counter, 16 onChange: setCounter 17 }), 18 name: createStrQueryParam({ 19 value: displayName, 20 onChange: setDisplayName 21 }) 22 }); 23 return ( 24 <> 25 <button onClick={() => setCounter(counter + 1)}>Increment Count</button> 26 <button onClick={() => setDisplayName('John Doe')}>Set Name</button> 27 <p>Count: {counter}</p> 28 <p>Name: {displayName}</p> 29 </> 30 ); 31}
Note that null
and undefined
values are not added to the query parameters. This is to prevent
the query parameters from being polluted with unnecessary values.
createNextRouterAdapter
The createNextRouterAdapter
function is a helper function for creating an adapter for the
NextQueryParamsProvider
. It takes a NextRouter
instance (returned by calling useRouter()
) as a
parameter and returns an adapter for the provider.
You can pass the second parameter to the createNextRouterAdapter
function to override the default
settings for the adapter:
1createNextRouterAdapter(router, {
2 // Override the default settings for the adapter
3 mode: 'merge', // default is 'reset', see advanced usage for more details
4 shallow: true, // default is false
5 replace: true // default is false, meaning router.push is used instead of router.replace
6});
You can even override the onChange
method of the adapter, taking entire control of handling the
urlQuery
:
1import { ParsedUrlQuery } from 'querystring';
2
3createNextRouterAdapter(router, {
4 // Override the default settings for the adapter
5 onChange: (urlQuery: ParsedUrlQuery) => {
6 // Do something with the urlQuery
7 // Update the query parameters your own way
8 }
9});
You can also use the useNextQueryParams
hook without a provider by passing the adapter as a
parameter:
1// pages/example.tsx 2import { useState } from 'react'; 3import { 4 createStrQueryParam, 5 createNumQueryParam, 6 useNextQueryParams, 7 createNextRouterAdapter 8} from 'use-next-query-params'; 9 10export default function ExamplePage() { 11 const [counter, setCounter] = useState(0); 12 const [displayName, setDisplayName] = useState(''); 13 useNextQueryParams( 14 { 15 count: createNumQueryParam({ 16 value: counter, 17 onChange: setCounter 18 }), 19 name: createStrQueryParam({ 20 value: displayName, 21 onChange: setDisplayName 22 }) 23 }, 24 createNextRouterAdapter(useRouter()) // pass the router adapter as the second argument 25 ); 26 return ( 27 <> 28 <button onClick={() => setCounter(counter + 1)}>Increment Count</button> 29 <button onClick={() => setDisplayName('John Doe')}>Set Name</button> 30 </> 31 ); 32}
By passing the adapter
prop to the NextQueryParamsProvider
(as shown above), you can also
override the default settings for the adapter provided in the provider (if it is present).
Note that all fields for the adapter
prop are optional in the hook. That means you can override
only the settings you want to change.
1// pages/example.tsx
2// ...
3
4export default function ExamplePage() {
5 const [counter, setCounter] = useState(0);
6 const [displayName, setDisplayName] = useState('');
7 useNextQueryParams(
8 {
9 count: createNumQueryParam({
10 value: counter,
11 onChange: setCounter
12 }),
13 name: createStrQueryParam({
14 value: displayName,
15 onChange: setDisplayName
16 })
17 },
18 {
19 // Override some of the settings for the adapter for this particular hook
20 mode: 'merge',
21 onChange: (urlQuery, isTriggeredByUrl) => {
22 // Do something with the urlQuery
23 // Update the urlQuery parameters your own way
24 }
25 }
26 );
27 return (
28 <>
29 <button onClick={() => setCounter(counter + 1)}>Increment Count</button>
30 <button onClick={() => setDisplayName('John Doe')}>Set Name</button>
31 </>
32 );
33}
This package also provides type-safe, convenient query parameter builders for most common use cases:
createStrQueryParam
createNumQueryParam
createBoolQueryParam
createJSONRecordQueryParam
createDateQueryParam
createStrArrayQueryParam
createNumArrayQueryParam
We use them to create query parameters for linking state variables inside the useNextQueryParams
hook.
createStrQueryParam
The createStrQueryParam
function creates a query parameter for a string state.
1// pages/example.tsx 2import { useNextQueryParams, createStrQueryParam } from 'use-next-query-params'; 3import { useState } from 'react'; 4 5export default function ExamplePage() { 6 const [name, setName] = useState('John Doe'); 7 8 useNextQueryParams({ 9 name: createStrQueryParam({ 10 value: name, 11 onChange: (value: string) => { 12 // Do something with the value 13 // Typically, you would update the state 14 setName(value); 15 }, 16 // optional, default is empty string '' 17 defaultValue: 'John Doe', 18 // optional, must be set to true if value can be `undefined` 19 optional: false, 20 // optional, must be set to true if value can be `null` 21 nullable: false, 22 // optional; if you provide a custom `deserialize` function, you should also provide a 23 // a custom `serialize` function. They should be inverses of each other. 24 // note that the return type here can be `undefined` or `null` if `optional` or `nullable` is set to true 25 deserialize: (value: string | string[]): string => { 26 // Do something with the value 27 // Typically, you would parse the value from the URL query to the desired state 28 if (Array.isArray(value)) { 29 return value[0] + '!'; 30 } 31 return value + '!'; 32 }, 33 // optional; if you provide a custom `serialize` function, you should also provide a 34 // a custom `deserialize` function. They should be inverses of each other. 35 // note that value here can be `undefined` or `null` if `optional` or `nullable` is set to true 36 serialize: (value: string): string | string[] | undefined => { 37 // Do something with the value 38 // Typically, you would stringify the value 39 // Return `undefined` if you want to remove the query parameter from the URL 40 return value.substring(0, value.length - 1); 41 } 42 }) 43 }); 44 45 // ... 46}
createNumQueryParam
The createNumQueryParam
function creates a query parameter for a number state.
1// pages/example.tsx
2import { useNextQueryParams, createNumQueryParam } from 'use-next-query-params';
3import { useState } from 'react';
4
5export default function ExamplePage() {
6 const [count, setCount] = useState(0);
7
8 useNextQueryParams({
9 count: createNumQueryParam({
10 value: count,
11 onChange: (value: number) => {
12 // Do something with the value
13 // Typically, you would update the state
14 setCount(value);
15 },
16 // optional, default is 0
17 defaultValue: 0,
18 // optional, must be set to true if value can be `undefined`
19 optional: false,
20 // optional, must be set to true if value can be `null`
21 nullable: false,
22 // optional; if you provide a custom `deserialize` function, you should also provide a
23 // a custom `serialize` function. They should be inverses of each other.
24 // note that the return type here can be `undefined` or `null` if `optional` or `nullable` is set to true
25 deserialize: (value: string | string[]): number => {
26 // Do something with the value
27 // Typically, you would parse the value from the URL query to the desired state
28 if (Array.isArray(value)) {
29 return Number(value[0]);
30 }
31 return Number(value);
32 },
33 // optional; if you provide a custom `serialize` function, you should also provide a
34 // a custom `deserialize` function. They should be inverses of each other.
35 // note that value here can be `undefined` or `null` if `optional` or `nullable` is set to true
36 serialize: (value: number): string | string[] | undefined => {
37 // Do something with the value
38 // Typically, you would stringify the value
39 // Return `undefined` if you want to remove the query parameter from the URL
40 return value.toString();
41 }
42 })
43 });
44
45 // ...
46}
createBoolQueryParam
The createBoolQueryParam
function creates a query parameter for a boolean state.
1// pages/example.tsx 2import { useNextQueryParams, createBoolQueryParam } from 'use-next-query-params'; 3import { useState } from 'react'; 4 5export default function ExamplePage() { 6 const [isDark, setIsDark] = useState(false); 7 8 useNextQueryParams({ 9 dark: createBoolQueryParam({ 10 value: isDark, 11 onChange: (value: boolean) => { 12 // Do something with the value 13 // Typically, you would update the state 14 setIsDark(value); 15 }, 16 // optional, default is false 17 defaultValue: false, 18 // optional, must be set to true if value can be `undefined` 19 optional: false, 20 // optional, must be set to true if value can be `null` 21 nullable: false, 22 // optional; if you provide a custom `deserialize` function, you should also provide a 23 // a custom `serialize` function. They should be inverses of each other. 24 // note that the return type here can be `undefined` or `null` if `optional` or `nullable` is set to true 25 deserialize: (value: string | string[]): boolean => { 26 // Do something with the value 27 // Typically, you would parse the value from the URL query to the desired state 28 if (Array.isArray(value)) { 29 return value[0] === 'true'; 30 } 31 return value === 'true'; 32 }, 33 // optional; if you provide a custom `serialize` function, you should also provide a 34 // a custom `deserialize` function. They should be inverses of each other. 35 // note that value here can be `undefined` or `null` if `optional` or `nullable` is set to true 36 serialize: (value: boolean): string | string[] | undefined => { 37 // Do something with the value 38 // Typically, you would stringify the value 39 // Return `undefined` if you want to remove the query parameter from the URL 40 if (v === undefined || v === null) { 41 return undefined; 42 } 43 if (props.withTime) { 44 return v.toISOString().split('.')[0]; 45 } 46 return v.toISOString().split('T')[0]; 47 } 48 }) 49 }); 50 51 // ... 52}
createJSONRecordQueryParam
The createJSONRecordQueryParam
function creates a query parameter for a JSON record state.
1// pages/example.tsx 2import { useNextQueryParams, createJSONRecordQueryParam } from 'use-next-query-params'; 3import { useState } from 'react'; 4 5export default function ExamplePage() { 6 const [user, setUser] = useState({ name: 'John Doe', age: 30 }); 7 8 useNextQueryParams({ 9 user: createJSONRecordQueryParam({ 10 value: user, 11 onChange: (value) => { 12 // Do something with the value 13 // Typically, you would update the state 14 setUser(value); 15 }, 16 // optional, default is {} 17 defaultValue: { name: 'John Doe', age: 30 }, 18 // optional, must be set to true if value can be `undefined` 19 optional: false, 20 // optional, must be set to true if value can be `null` 21 nullable: false, 22 // optional; if you provide a custom `deserialize` function, you should also provide a 23 // a custom `serialize` function. They should be inverses of each other. 24 // note that the return type here can be `undefined` or `null` if `optional` or `nullable` is set to true 25 deserialize: (value: string | string[]): Record<string, any> => { 26 // Do something with the value 27 // Typically, you would parse the value from the URL query to the desired state 28 if (Array.isArray(value)) { 29 return new Date(value[0]); 30 } 31 return new Date(value); 32 }, 33 // optional; if you provide a custom `serialize` function, you should also provide a 34 // a custom `deserialize` function. They should be inverses of each other. 35 // note that value here can be `undefined` or `null` if `optional` or `nullable` is set to true 36 serialize: (value: Record<string, any>): string | string[] | undefined => { 37 // Do something with the value 38 // Typically, you would stringify the value 39 // Return `undefined` if you want to remove the query parameter from the URL 40 if (v === undefined || v === null) { 41 return undefined; 42 } 43 return JSON.stringify(v); 44 } 45 }) 46 }); 47 48 // ... 49}
createDateQueryParam
The createDateQueryParam
function creates a query parameter for a date state.
1// pages/example.tsx 2import { useNextQueryParams, createDateQueryParam } from 'use-next-query-params'; 3import { useState } from 'react'; 4 5export default function ExamplePage() { 6 const [date, setDate] = useState(new Date('2021-01-01')); 7 8 useNextQueryParams({ 9 date: createDateQueryParam({ 10 value: date, 11 onChange: (value: Date) => { 12 // Do something with the value 13 // Typically, you would update the state 14 setDate(value); 15 }, 16 // optional, default is new Date() 17 defaultValue: new Date(), 18 // optional, default is false 19 // setting it to true will include the time in the ISO string format, i.e. YYYY-MM-DDTHH:mm:ss 20 // setting it to false will only include the date in the ISO string format, i.e. YYYY-MM-DD 21 withTime: true, 22 // optional, must be set to true if value can be `undefined` 23 optional: false, 24 // optional, must be set to true if value can be `null` 25 nullable: false, 26 // optional; if you provide a custom `deserialize` function, you should also provide a 27 // a custom `serialize` function. They should be inverses of each other. 28 // note that the return type here can be `undefined` or `null` if `optional` or `nullable` is set to true 29 deserialize: (value: string | string[]): Date => { 30 // Do something with the value 31 // Typically, you would parse the value from the URL query to the desired state 32 if (Array.isArray(value)) { 33 return new Date(value[0]); 34 } 35 return new Date(value); 36 }, 37 // optional; if you provide a custom `serialize` function, you should also provide a 38 // a custom `deserialize` function. They should be inverses of each other. 39 // note that value here can be `undefined` or `null` if `optional` or `nullable` is set to true 40 serialize: (value: Date): string | string[] | undefined => { 41 // Do something with the value 42 // Typically, you would stringify the value 43 // Return `undefined` if you want to remove the query parameter from the URL 44 if (v === undefined || v === null) { 45 return undefined; 46 } 47 if (props.withTime) { 48 return v.toISOString().split('.')[0]; 49 } 50 return v.toISOString().split('T')[0]; 51 } 52 }) 53 }); 54 55 // ... 56}
createStrArrayQueryParam
The createStrArrayQueryParam
function creates a query parameter for an array of strings.
1// pages/example.tsx
2import { useNextQueryParams, createStrArrayQueryParam } from 'use-next-query-params';
3import { useState } from 'react';
4
5export default function ExamplePage() {
6 const [tags, setTags] = useState(['tag1', 'tag2']);
7
8 useNextQueryParams({
9 tags: createStrArrayQueryParam({
10 value: tags,
11 onChange: (value: string[]) => {
12 // Do something with the value
13 // Typically, you would update the state
14 setTags(value);
15 },
16 // optional, default is []
17 defaultValue: ['tag1', 'tag2'],
18 // optional, must be set to true if value can be `undefined`
19 optional: false,
20 // optional, must be set to true if value can be `null`
21 nullable: false,
22 // optional; if you provide a custom `deserialize` function, you should also provide a
23 // a custom `serialize` function. They should be inverses of each other.
24 // note that the return type here can be `undefined` or `null` if `optional` or `nullable` is set to true
25 deserialize: (value: string | string[]): string[] => {
26 // Do something with the value
27 // Typically, you would parse the value from the URL query to the desired state
28 if (Array.isArray(v)) {
29 props.onChange(v);
30 } else {
31 props.onChange([v]);
32 }
33 },
34 // optional; if you provide a custom `serialize` function, you should also provide a
35 // a custom `deserialize` function. They should be inverses of each other.
36 // note that value here can be `undefined` or `null` if `optional` or `nullable` is set to true
37 serialize: (value: string[]): string | string[] | undefined => {
38 // Do something with the value
39 // Typically, you would stringify the value
40 // Return `undefined` if you want to remove the query parameter from the URL
41 return v;
42 }
43 })
44 });
45
46 // ...
47}
createNumArrayQueryParam
The createNumArrayQueryParam
function creates a query parameter for an array of numbers.
1// pages/example.tsx 2import { useNextQueryParams, createNumArrayQueryParam } from 'use-next-query-params'; 3import { useState } from 'react'; 4 5export default function ExamplePage() { 6 const [numbers, setNumbers] = useState([1, 2, 3]); 7 8 useNextQueryParams({ 9 numbers: createNumArrayQueryParam({ 10 value: numbers, 11 onChange: (value: number[]) => { 12 // Do something with the value 13 // Typically, you would update the state 14 setNumbers(value); 15 }, 16 // optional, default is [] 17 defaultValue: [1, 2, 3], 18 // optional, must be set to true if value can be `undefined` 19 optional: false, 20 // optional, must be set to true if value can be `null` 21 nullable: false, 22 // optional; if you provide a custom `deserialize` function, you should also provide a 23 // a custom `serialize` function. They should be inverses of each other. 24 // note that the return type here can be `undefined` or `null` if `optional` or `nullable` is set to true 25 deserialize: (value: string | string[]): number[] => { 26 // Do something with the value 27 // Typically, you would parse the value from the URL query to the desired state 28 if (Array.isArray(v)) { 29 return v.map((v) => Number(v)); 30 } 31 return [Number(v)]; 32 }, 33 // optional; if you provide a custom `serialize` function, you should also provide a 34 // a custom `deserialize` function. They should be inverses of each other. 35 // note that value here can be `undefined` or `null` if `optional` or `nullable` is set to true 36 serialize: (value: number[]): string | string[] | undefined => { 37 // Do something with the value 38 // Typically, you would stringify the value 39 // Return `undefined` if you want to remove the query parameter from the URL 40 return v.map((v) => v.toString()); 41 } 42 }) 43 }); 44 45 // ... 46}
The adapter interface is defined as follows:
1import { ParsedUrlQuery } from 'querystring'; 2 3type NextQueryParamsAdapterMode = 'reset' | 'merge'; 4 5type NextQueryParamsAdapter = { 6 readonly isRouterReady: boolean; 7 readonly urlQuery: ParsedUrlQuery; 8 readonly onChange: (urlQuery: ParsedUrlQuery, isTriggeredByUrl: boolean) => void; 9 readonly mode?: NextQueryParamsAdapterMode; 10 readonly customSerializeQueryParam?: SerializeQueryParam; 11};
You can provide a custom adapter to the NextQueryParamsProvider
provider or useNextQueryParams
hook (as the second argument). This is useful if you are using a router different from Next.js
built-in router.
1// app.jsx 2import { NextQueryParamsProvider } from 'use-next-query-params'; 3import router from 'some-router'; // Your router 4 5export default function App() { 6 const routerAdapter = { 7 // if your app is client-side only, you can set this to true as router is always ready 8 isRouterReady: true, 9 // your router's query object 10 urlQuery: router.query, 11 // your router's push/replace method 12 onChange: (urlQuery, isTriggeredByUrl) => { 13 // if the urlQuery is changed by the user navigation, use 'replace' to avoid adding a new entry to the history 14 const routingMethod = isTriggeredByUrl ? 'replace' : 'push'; 15 router[routingMethod]({ urlQuery }); 16 }, 17 // optional, default is 'reset' 18 mode: 'merge' 19 }; 20 return ( 21 <NextQueryParamsProvider adapter={routerAdapter}> 22 <Component /> 23 </NextQueryParamsProvider> 24 ); 25}
mode
The mode
property of the adapter can be set to one of the following values:
reset
: The query parameters are reset to the default values when the state changes.merge
: The query parameters are merged with the default values when the state changes.See the demo for an example of each mode.
useNextQueryParams
without builder functionsYou can also use useNextQueryParams
without builder functions by passing objects like the
following:
1// pages/example.tsx 2import { useNextQueryParams } from 'use-next-query-params'; 3import { useState } from 'react'; 4 5export default function ExamplePage() { 6 const [name, setName] = useState('John Doe'); 7 const [age, setAge] = useState(30); 8 9 useNextQueryParams<{ 10 name: string; // you can explicitly define typings for the query parameters here; the hook will try to infer them if you don't 11 age: number; 12 }>({ 13 name: { 14 value: name, 15 onChange: (value: string) => { 16 // Do something with the value 17 // Typically, you would deserialize the value from the URL query to the desired state 18 setName(yourDeserializationFunctionForStrings(value)); 19 }, 20 onReset: () => { 21 // Do something when the value is reset 22 // This will happen when `mode` is set to `reset` and the query parameter is removed from the URL 23 // Typically, you would update the state to its default value 24 setName('John Doe'); 25 }, 26 // optional; if you provide a custom `serialize` function, you should also provide a 27 // a custom `deserialize` function used in the `onChange` function (as shown above). They should be inverses of each other. 28 serialize: (value: string): string | string[] | undefined => { 29 // Do something with the value 30 // Typically, you would stringify the value 31 // Return `undefined` if you want to remove the query parameter from the URL 32 return value; 33 } 34 }, 35 age: { 36 value: age, 37 onChange: (value: number) => { 38 // Do something with the value 39 // Typically, you would deserialize the value from the URL query to the desired state 40 setAge(yourDeserializationFunctionForNumbers(value)); 41 }, 42 onReset: () => { 43 // Do something when the value is reset 44 // This will happen when `mode` is set to `reset` and the query parameter is removed from the URL 45 // Typically, you would update the state to its default value 46 setAge(30); 47 }, 48 // optional; if you provide a custom `serialize` function, you should also provide a 49 // a custom `deserialize` function used in the `onChange` function (as shown above). They should be inverses of each other. 50 serialize: (value: number): string | string[] | undefined => { 51 // Do something with the value 52 // Typically, you would stringify the value 53 // Return `undefined` if you want to remove the query parameter from the URL 54 return value.toString(); 55 } 56 } 57 }); 58 59 // ... 60}
The package also exports a createQueryParamFunctionFactory
function that can be used to create
your own builder functions. See example usage below:
1// utils/createMyQueryParam.ts 2 3import { useNextQueryParams, createQueryParamFunctionFactory } from 'use-next-query-params'; 4 5// Note that `props` have the below type 6// { 7// value: AllowedType<TData, TNullable, TOptional>; 8// onChange: (value: AllowedType<TData, TNullable, TOptional>) => void; 9// /** 10// * Deserialize a value from a parsed URL query into the type of the query param. 11// * @note If you are using a custom `serialize` function, you should also provide a custom `deserialize` function. They must be inverses of each other. 12// */ 13// deserialize?: (value: string | string[]) => AllowedType<TData, TNullable, TOptional>; 14// /** 15// * Serialize a value from the query param into a parsed URL query (i.e., string or array of strings). 16// * @note If you are using a custom `deserialize` function, you should also provide a custom `serialize` function. They must be inverses of each other. 17// */ 18// serialize?: (value: AllowedType<TData, TNullable, TOptional>) => string | string[] | undefined; 19// defaultValue?: AllowedType<TData, TNullable, TOptional>; 20// nullable?: TNullable; 21// optional?: TOptional; 22// } 23export const createMyQueryParam = createQueryParamFunctionFactory<MyOwnType>((props) => ({ 24 // provide your own implementation in the below fields 25 26 // note that the value here is of type `AllowedType<TData, TNullable, TOptional>` 27 // TData is the type of the query param, here it is `MyOwnType` 28 // TNullable and TOptional are boolean values that indicate whether the query param is nullable and/or optional 29 value: props.value, 30 // `onChange` is a function that takes a value of type `AllowedType<TData, TNullable, TOptional>` and updates the URL query param 31 onChange: props.onChange, 32 // optional, `defaultValue` is the default value of the query param 33 defaultValue: props.defaultValue, 34 // optional, `optional` is a boolean value that indicates whether the query param is optional 35 optional: props.optional, 36 // optional, `nullable` is a boolean value that indicates whether the query param is nullable 37 nullable: props.nullable, 38 // optional, `deserialize` is a function that takes a value of type `string | string[]` and deserializes it into a value of type `AllowedType<TData, TNullable, TOptional>` 39 deserialize: props.deserialize, 40 // optional, `serialize` is a function that takes a value of type `AllowedType<TData, TNullable, TOptional>` and serializes it into a value of type `string | string[] | undefined` 41 serialize: props.serialize 42}));
isStable
value returned by useNextQueryParams
The useNextQueryParams
hook returns a isStable
value, which is a boolean indicating whether the
query parameters and their corresponding states are fully initialized. This could be useful if you
want to prevent certain actions from being performed before the initialization is complete.
1// pages/example.tsx 2 3// ... 4export default function ExamplePage() { 5 const [counter, setCounter] = useState(0); 6 const [displayName, setDisplayName] = useState(''); 7 const { isStable } = useNextQueryParams({ 8 count: createNumQueryParam({ 9 value: counter, 10 onChange: setCounter 11 }) 12 }); 13 return ( 14 <> 15 <button 16 onClick={() => { 17 // prevent incrementing the counter if the query parameters are not stable 18 // this can be useful if you or your users use a browser automation tool 19 // to change states immediately after the page loads 20 if (isStable) { 21 setCounter(counter + 1); 22 } 23 }} 24 > 25 Increment Count 26 </button> 27 <p>Count: {counter}</p> 28 </> 29 ); 30}
No vulnerabilities found.
No security vulnerabilities found.