wouter icon indicating copy to clipboard operation
wouter copied to clipboard

Add support for query parameter destructuring

Open andyrichardson opened this issue 3 years ago • 4 comments

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)

andyrichardson avatar Feb 26 '21 12:02 andyrichardson

you can custom your own location hook like this

cbbfcd avatar Apr 19 '21 09:04 cbbfcd

I just made a wrapper hook for this. See here https://github.com/molefrog/wouter/issues/58#issuecomment-855215736

ryanking1809 avatar Jun 06 '21 04:06 ryanking1809

Nice, @ryanking1809 ! It feels like this could be baked in, no? I'm happy to open a PR if it's welcome 🙂

shanepoints avatar Oct 12 '21 21:10 shanepoints

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!)

HansBrende avatar Jan 31 '22 15:01 HansBrende

@andyrichardson you can now do this:

import {useSearch} from 'wouter/use-location';
const search = useSearch();
const searchParams = new URLSearchParams(search);

HansBrende avatar Jan 11 '23 21:01 HansBrende

That's great news! Thanks for sharing

andyrichardson avatar Jan 11 '23 22:01 andyrichardson