Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Redirect to same path with different search querystring #105

Open
Mobiletainment opened this issue Jan 11, 2022 · 1 comment
Open

Redirect to same path with different search querystring #105

Mobiletainment opened this issue Jan 11, 2022 · 1 comment

Comments

@Mobiletainment
Copy link

Description

I am running into an issue with a guard that redirects to the same path.
What I'd like to do in the guard is to check if the route was called without a search query parameter.
If that's the case, a default search query parameter is applied and next.redirect(samePath?param=new) is invoked.

Steps to reproduce

Basic example:

const requireViewParameter = (to: GuardToRoute, _from: GuardFunctionRouteProps | null, next: Next) => {
    const query = to.location.search;
    if (query.length > 0) {
      return next();
    }

    console.log('No id was was set, redirecting to the default view');
    
    next.redirect({
      ...to.location,
      search: `?id=1`,
    });
};

<GuardProvider guards={[requireViewParameter]}>
    <GuardedRoute exact path={'view'} component={View} />
</GuardProvider>

Open the application and set the path to /view without any query parameters

Expected result

The guard runs and the URL is updated to /view?id=1

Actual result

The guard runs and invokes the redirect, but the new query parameter is not applied. The app stays on /view instead.

Environment

  • OS: Windows 10
  • Browser and its version: Chrome Canary 99.0.4819.0 (Official Build) 64-bit
  • React Router DOM version:
    • "react": "17.0.2"
    • "react-router-dom": "5.3.0"
    • "react-router-guards": "^1.0.2"
@Mobiletainment
Copy link
Author

It's worth noting that it can be achieved differently though.
If I mutate the search property and just call next() it works:

const requireViewParameter = (to: GuardToRoute, _from: GuardFunctionRouteProps | null, next: Next) => {
    to.location.search = to.location.search || `?id=1`;
    return next();
};

But this feels rather hacky to me, so I would love to have your opinion on that.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant