Sync URL search params
- Initialize the URL query params with default ones
- Update query params on demand
- Using
npm
npm install --save sync-url-search-params
- Using
yarn
yarn add sync-url-search-params
import SyncURLSearchParams from 'sync-url-search-params'
const susp = new SyncURLSearchParams({ foo: 'bar' })
// Or
const foo = new SyncURLSearchParams(window.location.search).get('foo')
function App() {
console.count('render count');
return (
<>
<pre>param `foo`: {susp.getParam('foo')}</pre>
<pre>location.search: {window.location.search}</pre>
<pre>state: {JSON.stringify(state)}</pre>
<pre>cache: {JSON.stringify(susp.getAllParams())}</pre>
<button onClick={() => susp.setParam('foo', 'baz')}>Change bar to baz</button>
<br/>
<button onClick={() => susp.clearParam('foo')}>Clear query param</button>
</>
)
}
-
SyncURLSearchParams(defaultParams: { [x: string | number | symbol]: string | number | boolean | null | undefined }, options?: { shouldKeepURLUndeclaredParams?: boolean }) => ({ getParam, getParams, getAllParams, setParam, setParams, clearParam, clearParams, setCallback })
Initialize the hook with default params.
Automatic URL query params synchronization will happen only once on mount.
And take the value from URL search params as priority if it exists.
-
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 | number | symbol, value: string | number | boolean | null | undefined, options?: { shouldKeepURLUndeclaredParams?: boolean }) => 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 | number | symbol, value: string | number | boolean | null | undefined>, options?: { shouldKeepURLUndeclaredParams?: boolean }) => 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, options?: { shouldKeepURLUndeclaredParams?: boolean }) => boolean
Clear specific key from query params. Same as
setParam
with empty value. -
clearParams: (keys?: string[], options?: { shouldKeepURLUndeclaredParams?: boolean }) => boolean
Clear a set of keys from query params. Same as
setParams
with empty values.If input is empty, all params will be cleared
-
setCallback<T>(callback: (result: boolean, params: T) => void, shouldInvokeCallbackImmediately?: boolean)
Set callback that invokes once change event happens (after initialization), and every time newly set if opt in.