molefrog / wouter

🥢 A minimalist-friendly ~2.1KB routing for React and Preact
https://npm.im/wouter
The Unlicense
6.41k stars 146 forks source link

Consider exposing `matchRoute` helper function #455

Closed acelaya closed 1 month ago

acelaya commented 1 month ago

I wanted to ask if you would consider exposing the matchRoute helper function that is internally used by useRoute and Switch.

I'm trying to create a custom hook which receives a list of routes in order to check which one matches, but this list of routes is dynamic, so it's not possible to call useRoute a bunch of times, since it needs to loop over the list of routes.

However, if matchRoute was exported by this package, it would allow userland programmatic logic like this:

import { matchRoute, useLocation, useRouter } from 'wouter-preact';

function useMatchingRoute(candidates: string[]): [string, Record] | undefined {
  const { parser } = useRouter();
  const [location] = useLocation();

  return useMemo(() => {
    for (const route of candidates) {
      const [matches, params] = matchRoute(parser, route, location);
      if (matches) {
        return [route, params];
      }
    }

    return undefined;
  }, [location, parser, candidates]);
}

I can provide a PR if you are ok with this.

molefrog commented 1 month ago

I wanted to ask if you would consider exposing the matchRoute helper function that is internally used by useRoute and Switch.

I'm trying to create a custom hook which receives a list of routes in order to check which one matches, but this list of routes is dynamic, so it's not possible to call useRoute a bunch of times, since it needs to loop over the list of routes.

However, if matchRoute was exported by this package, it would allow userland programmatic logic like this:

import { matchRoute, useLocation, useRouter } from 'wouter-preact';

function useMatchingRoute(candidates: string[]): [string, Record] | undefined {
  const { parser } = useRouter();
  const [location] = useLocation();

  return useMemo(() => {
    for (const route of candidates) {
      const [matches, params] = matchRoute(parser, route, location);
      if (matches) {
        return [route, params];
      }
    }

    return undefined;
  }, [location, parser, candidates]);
}

I can provide a PR if you are ok with this.

Hey @acelaya, thank you for suggesting this. I think it makes a lot of sense, so feel free to open a pull request.

acelaya commented 1 month ago

Hey @acelaya, thank you for suggesting this. I think it makes a lot of sense, so feel free to open a pull request.

Just created it https://github.com/molefrog/wouter/pull/456

molefrog commented 4 weeks ago

Just published the new version.