react-router-guards
react-router-guards copied to clipboard
Resolve infinite redirects, broken redirects for same paths with different params
Description
In our render resolution of Guard, we included a method to resolve redirecting to the same path.
Unfortunately, this didn't actually account for a redirect to the same path with different parameters. To fix this, we now perform a check for infinite redirection and only perform redirects in the render
Related issues
Fixes #55
What this does
- Adds a check for infinite renders in
validateRouteand throws up an error if so - Removes path checking in
routeRedirectcase of render—now only renders theRedirectcomponent - Update default error from
'Not found.'torrg/error(to match other errors)
How to test
Following the example in #55:
-
Pull down the repo locally and set up the dev server (
npm i,npm run bootstrap,npm start) -
In
src/router/index.tsx, add the following guard function:
const invalidName: GuardFunction = (to, from, next) => {
const { name } = to.match.params;
if (name === 'test') {
next.redirect('/charmander');
} else {
next();
}
};
<GuardedRoute
path="/:name"
exact
component={Detail}
- guards={[waitOneSecond, detailBeforeEnter]}
+ guards={[invalidName, waitOneSecond, detailBeforeEnter]}
/>
- Visit http://localhost:3001/test. Confirm the redirect resolves correctly to
/charmander - Update the
invalidNameguard to cause an infinite redirect to/test - Confirm the app doesn't infinitely redirect + break, but rather throws up an error page
Additional Notes
Currently the routes are only "matched" by their pathname—something that will be changed by #39 (or similar functionality changes from that)