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 rules in routeMap #461

Open
stefan-toubia opened this issue Jun 22, 2020 · 0 comments
Open

Redirect rules in routeMap #461

stefan-toubia opened this issue Jun 22, 2020 · 0 comments

Comments

@stefan-toubia
Copy link

I recently needed to add some redirect to some of my routes and was surprised that there wasn't an existing solution. Here's what I ended up with, works great for me and is pretty straightforward.

const routesMap = {
  HOME: "/",
  SOMEWHERE: {
    path: "/somewhere",
    redirect: (getState) => {
      const { hasPermission } = selectConfig(getState());
      if (!hasPermission) {
        return "NOT_FOUND";
      }
    },
  },
}

const { reducer, middleware, enhancer, initialDispatch } = connectRoutes(
  routesMap,
  {
    initialDispatch: false,
    onBeforeChange: (dispatch, getState, { action }) => {
      const redirectRoute = routesMap[action.type]?.redirect?.(getState);
      if (redirectRoute) {
        dispatch(redirect({ type: redirectRoute, payload: action.payload }));
      }
    },
  }
);

This adds a redirect function prop to routesMap, which will be used in onBeforeChange to redirect if redirect returns a value. Note that in my case I needed to use initialDispatch because I need to fetch some user data before I can execute the redirect logic.

This is working pretty well for my current use case but it could probably be more robust. redirect could also accept the payload or action as a second arg. Maybe it would also make sense for redirect to return an action instead of the action type string for better control over redirecting the payload or metadata.

If this approach makes sense it would be nice to have it integrated into connectRoutes. I noticed this was an active help topic for wanted PRs, I can open a PR if it will be helpful.

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