wouter
wouter copied to clipboard
Add support for query parameter destructuring
About
It would be nice if wouter could include query parameter destructuring
Example
const { pathName, search, searchParams } = useLocation();
// `https://someplace.com/test?a=1234`
console.log(pathName) // `/test`(like browser spec)
console.log(search) // `?a=1234` (like browser spec)
console.log(searchParams) // `{ a: 1234 }` (convenience fn)
you can custom your own location hook like this
I just made a wrapper hook for this. See here https://github.com/molefrog/wouter/issues/58#issuecomment-855215736
Nice, @ryanking1809 ! It feels like this could be baked in, no? I'm happy to open a PR if it's welcome 🙂
The correct way to do this would be something like the example shown here: https://github.com/molefrog/wouter/issues/232
Tbh, not sure why search changing is causing re-rendering by default... that seems misguided. Since there's currently no subscribe
function exported, could easily write our own:
const events = ["popstate", "pushState", "replaceState", "hashchange"];
function subscribe(callback: () => void) {
for (const event of events) {
window.addEventListener(event, callback);
}
return () => {
for (const event of events) {
window.removeEventListener(event, callback);
}
}
}
function getCurrentValueOfMyParam() {
return someFunctionOf(window.location);
}
And now we can simply do...
const myParam = React.useSyncExternalStore(subscribe, getCurrentValueOfMyParam);
No re-rendering if myParam
hasn't changed, even if a million other things in the url have!
(Notice: no mucking with Router
is necessary at all!)
@andyrichardson you can now do this:
import {useSearch} from 'wouter/use-location';
const search = useSearch();
const searchParams = new URLSearchParams(search);
That's great news! Thanks for sharing