Sync URL query params. Zero dependency.
npm install sync-url-search-params> Sync URL search params
- Initialize the URL query params with default ones
- Update query params on demand
---
- Using npm
``Bash`
npm install --save sync-url-search-params
- Using yarn
`Bash`
yarn add sync-url-search-params
---
`TSX
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 (
<>
param foo: {susp.getParam('foo')}location.search: {window.location.search}state: {JSON.stringify(state)}cache: {JSON.stringify(susp.getAllParams())}
>
)
}
`
---
1. 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.
2. getParam: (key: string) => string
Get specific key from query params. Autosuggestion mapped to keys of the default params.
3. getParams: (...keys: string[]) => Object
Get a set of params.
4. getAllParams: () => Object
Get all query params. The result contains all records with keys of the default params except those that were cleared.
5. 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 setfalse
- Otherwise if window.history.pushState is not available
6. setParams: (Object
Set a set of records. Empty values (empty string, null, undefined) will be cleared.
- Return true if successfully setfalse
- Otherwise if window.history.pushState is not available
7. clearParam: (key: string, options?: { shouldKeepURLUndeclaredParams?: boolean }) => boolean
Clear specific key from query params. Same as setParam with empty value.
8. 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
9. setCallback
Set callback that invokes once change event happens (after initialization), and every time newly set if opt in.