@lindeneg/query-params
TypeScript icon, indicating that this package has built-in type declarations

1.1.4 • Public • Published

@lindeneg/query-params

typescript bundle-size license

Sandbox


React hook using URLSearchParams

Installation

yarn add @lindeneg/query-params


Arguments

Name Required Ref Type Description
params Y T Record<string, string> object with param keys and optional default values

Return

Object with properties:

Name Type Description
values T object with current param values
onParamChange (type: keyof T, value: string) => void; change param value

Usage

function SomeComponent() {
  const { values, onParamChange } = useQueryParams({
    id: '',
    context: '',
    // optional default value
    sort: 'desc',
  });
}

This will result in window.location.search having the value ?sort=desc. If sort also was an empty string, then window.location.search would be empty.

Update param as follows:

onParamChange('context', 'products');

Now window.location.search will be ?context=products&sort=desc

To remove it, use an empty string:

onParamChange('context', '');

Now window.location.search will be ?sort=desc

If default values are specified, an empty string will not remove the key but rather use the default value instead.

So, if sort is changed

onParamChange('sort', 'asc');

Then window.location.search will of course be ?sort=asc

However, if the key is removed

onParamChange('sort', '');

The default value will be used and window.location.search will be ?sort=desc

Versions

Current Tags

  • Version
    Downloads (Last 7 Days)
    • Tag
  • 1.1.4
    1
    • latest

Version History

Package Sidebar

Install

npm i @lindeneg/query-params

Weekly Downloads

1

Version

1.1.4

License

MIT

Unpacked Size

6.06 kB

Total Files

6

Last publish

Collaborators

  • christianlindeneg