Installations
npm install use-url-search-params
Developer
rudyhuynh
Developer Guide
Module System
CommonJS, UMD
Min. Node Version
Typescript Support
No
Node Version
14.18.1
NPM Version
7.24.2
Statistics
64 Stars
129 Commits
5 Forks
3 Watching
6 Branches
3 Contributors
Updated on 21 Nov 2024
Languages
TypeScript (50.08%)
JavaScript (33.41%)
HTML (10.58%)
CSS (5.86%)
Shell (0.08%)
Total Downloads
Cumulative downloads
Total Downloads
654,026
Last day
15.1%
772
Compared to previous day
Last week
-12.9%
3,258
Compared to previous week
Last month
16.9%
15,601
Compared to previous month
Last year
-25.6%
150,732
Compared to previous year
Daily Downloads
Weekly Downloads
Monthly Downloads
Yearly Downloads
Peer Dependencies
1
Dev Dependencies
22
useUrlSearchParams()
A React Hook to use URL query string as a state management
Why you need this
- Your app need to persist its state after user refresh the page (used for simple, non-sensitive data).
- Some page settings (ex: table filter, sorting, paging, etc.) should be saved in the URL so that user can easily pass to others. e.g. Tester can easily send a URL of a page to developer with very least reproduce steps.
- You want to do something (request new data, etc.) every time some URL query value changes.
- Combine all of the above with a URL query as a single source of truth.
Installation
npm install use-url-search-params
or
yarn add use-url-search-params
How to use
For most of the time you will do something like this:
1import React from "react"; 2import { useUrlSearchParams } from "use-url-search-params"; 3 4function App() { 5 // Your page URL will be like this by default: http://my.page?checked=true 6 const [params, setParams] = useUrlSearchParams({ checked: true }); 7 8 React.useEffect(() => { 9 // do something when `params.checked` is updated. 10 }, [params.checked]); 11 12 return ( 13 <div> 14 <input type="checkbox" checked={params.checked} onChange={(e) => setParams({ checked: e.target.checked })} /> 15 </div> 16 ); 17}
How to control the value parsed from URL query
By default, all values parsed from URL query are string. In case you want to get boolean or number value, pass a second argument to useUrlSearchParams()
to specify data type you want to get from params
object. Here is an example:
1const initial = { 2 y: "option1", 3}; 4const types = { 5 x: Number, 6 y: Boolean, 7 z: Date, 8 t: ["option1", "option2", "option3"], 9}; 10const [params, setParams] = useUrlSearchParams(initial, types); 11 12// `params.x` will be number (or NaN) 13// `params.y` will be one of [undefined, true, false] 14// `params.z` will be instance of Date (can be Invalid Date) 15// `params.t` will be one of ["option1", "option2", "option3"] (can be `undefined` if not specified in `initial`)
Complex data structure
Although you can use JSON.parse()
and JSON.stringify()
to get/set arbitrary serializable data to URL query, it is not recommended. URL query is a good place to store and persist page settings as key/value pairs such as table filter, sorting, paging, etc. We should keep it that way for simplicity. For complex data structure, you should consider using other state management for better performance, security and flexibility.
WARNING: Be aware of XSS attack. Be careful to validate values from URL query before using it by either using
types
- the second parameter passed touseUrlSearchParams()
or validate them yourself if neccessary.
But if you still insist, here is an example:
1function App() { 2 const [params, setParams] = useUrlSearchParams( 3 {}, 4 { 5 complexData: (dataString) => { 6 try { 7 return JSON.parse(dataString); 8 } catch (e) { 9 return {}; 10 } 11 }, 12 } 13 ); 14 15 const onSetParams = (data) => { 16 setParams({ complexData: JSON.stringify(data) }); 17 }; 18 19 return <div>{/*...*/}</div>; 20}
React Router
Should just work with React Router or any routing system. Just make sure that your component re-render whenever route changes.
API
- useUrlSearchParams([initial, types, replace])
initial
(optional | Object): To set default values for URL query string.types
(optional | Object): Has similar shape withinitial
, help to resolve values from URL query string. Supported types:String
(default)Number
Bool
Date
-Date​.prototype​.toISOString()
is used to parse date to string, e.g date string in your URL query is zero UTC offset- Array of available string values (like enum)
- A custom resolver function
replace
(optional | boolean | default: false): If true, will callhistor#replaceState()
instead ofhistory#pushState()
on url search param change.
Read more (for maintainers)
This library is built base on URLSearchParams interface
License
MIT
No vulnerabilities found.
Reason
no binaries found in the repo
Reason
license file detected
Details
- Info: project has a license file: License:0
- Info: FSF or OSI recognized license: MIT License: License:0
Reason
Found 1/26 approved changesets -- score normalized to 0
Reason
0 commit(s) and 0 issue activity found in the last 90 days -- score normalized to 0
Reason
no effort to earn an OpenSSF best practices badge detected
Reason
security policy file not detected
Details
- Warn: no security policy file detected
- Warn: no security file to analyze
- Warn: no security file to analyze
- Warn: no security file to analyze
Reason
project is not fuzzed
Details
- Warn: no fuzzer integrations found
Reason
SAST tool is not run on all commits -- score normalized to 0
Details
- Warn: 0 commits out of 5 are checked with a SAST tool
Reason
13 existing vulnerabilities detected
Details
- Warn: Project is vulnerable to: GHSA-67hx-6x53-jw92
- Warn: Project is vulnerable to: GHSA-93q8-gq69-wqmw
- Warn: Project is vulnerable to: GHSA-grv7-fg5c-xmjg
- Warn: Project is vulnerable to: GHSA-3xgq-45jj-v275
- Warn: Project is vulnerable to: GHSA-9c47-m6qq-7p4h
- Warn: Project is vulnerable to: GHSA-952p-6rrq-rcjv
- Warn: Project is vulnerable to: GHSA-f8q6-p94x-37v3
- Warn: Project is vulnerable to: GHSA-xvch-5gv4-984h
- Warn: Project is vulnerable to: GHSA-gcx4-mw62-g8wm
- Warn: Project is vulnerable to: GHSA-c2qf-rxjj-qqgw
- Warn: Project is vulnerable to: GHSA-72xf-g2v4-qvf3
- Warn: Project is vulnerable to: GHSA-j8xg-fqg3-53r7
- Warn: Project is vulnerable to: GHSA-3h5v-q93c-6h6q
Score
2
/10
Last Scanned on 2024-11-18
The Open Source Security Foundation is a cross-industry collaboration to improve the security of open source software (OSS). The Scorecard provides security health metrics for open source projects.
Learn MoreOther packages similar to use-url-search-params
@umijs/use-params
[![GitHub license](https://img.shields.io/github/license/Naereen/StrapDown.js.svg)](https://github.com/rudyhuynh/use-url-search-params/blob/master/License)
@ungap/url-search-params
The URLSearchParams polyfill.
url-search-params-polyfill
a simple polyfill for javascript URLSearchParams
url
The core `url` packaged standalone for use with Browserify.