use-sync-query-params v0.1.7
use-sync-query-params
Sync React props/states to URL query params.
Purposes
- Initialize the URL query params with default ones.
- The default params can come from any source:
redux
,props
, computed variables...
- The default params can come from any source:
- Update query params on demand
Installation
- Using
npm
npm install --save use-sync-query-params
- Using
yarn
yarn add use-sync-query-params
Usage examples
import useSyncQueryParams from 'use-sync-query-params'
export default function App(props) {
const params = useSyncQueryParams({ foo: 'bar' })
// Or
const params = useSyncQueryParams({ foo: props.foo })
// Or
const foo = new URLSearchParams(window.location.search).get('foo')
const params = useSyncQueryParams({ foo })
return (
<>
<p>{params.getParam('foo')}</p>
<p>{window.location.search}</p>
<pre>{JSON.stringify(params.getAllParams())}</pre>
<br/>
<button onClick={() => params.setParam('foo', 'baz')}>Change bar to baz</button>
<br/>
<button onClick={() => params.clearParam('foo')}>Clear query param</button>
</>
)
}
Demo
APIs
useSyncQueryParams(defaultParams: { [x: string]: string | number | boolean | null | undefined }) => ({ getParam, getAllParams, setParam, setParams, clearParam })
Initial the hook with default params. Automatic URL query params synchronization will happen only once on mount.
getParam: (key: string) => string
Get specific key from query params. Autosuggestion mapped to keys of the default params.
getParams: (...keys: string[]) => Object<string, string>
Get a set of params.
getAllParams: () => Object
Get all query params. The result contains all records with keys of the default params except those that were cleared.
setParam: (key: string, value: string | number | boolean | null | undefined) => boolean
Set a specific key with a value. Empty values (empty string, null, undefined) will be cleared.
- Return
true
if successfully set - Otherwise
false
ifwindow.history.pushState
is not available
- Return
setParams: (Object<key: string, value: string | number | boolean | null | undefined>) => boolean
Set a set of records. Empty values (empty string, null, undefined) will be cleared.
- Return
true
if successfully set - Otherwise
false
ifwindow.history.pushState
is not available
- Return
clearParam: (key: string) => boolean
Clear specific key from query params. Same as
setParam
with empty value.clearParams: (...keys: string[]) => boolean
Clear a set of keys from query params. Same as
setParams
with empty values.