lulu33
lulu33

Reputation: 327

React-Router redirect after auth I'm getting infinite loop of renders

I'm getting an infinite loop when trying to redirect users to wanted path after obligatory login.

My Private Route, when i add state: { from: props.location }, I get infinite loop.

const PrivateRoute = ({
  component: Component,
  exact,
  path,
}: RouteProps): JSX.Element => {
  if (!Component) return <div />;
  const classes = useStyles();
  const auth = useSelector((state: RootState) => state.auth);
  return (
    <Route
      path={path}
      exact={exact}
      render={(props) => (auth.loading ? (
        <Backdrop className={classes.backdrop} open>
          <CircularProgress color="inherit" />
        </Backdrop>
      ) : auth.isAuthenticated ? (
        <Component {...props} />
      ) : (
        <Redirect to={{
          pathname: '/login',
          state: { from: props.location },
        }}
        />
      ))}
    />
  );
};

My Switch

<Router history={history}>
        <ThemeProvider theme={theme}>
          <CssBaseline />
          <Alert th={ui.darkTheme} />
          <UpdateApp />
          <Route path="/login" exact component={Login} />
          <Switch>
            <PrivateRoute path="/" exact component={Homepage} />
            <PrivateRoute path="/info" exact component={Infos} />
            <PrivateRoute path="/info/add" exact component={AddInfo} />
            <PrivateRoute path="/info/:id" exact component={ShowInfo} />
            <PrivateRoute path="/info/:id/edit" exact component={EditInfo} />
            <PrivateRoute component={Four} />
          </Switch>
        </ThemeProvider>
      </Router>

Upvotes: 2

Views: 710

Answers (1)

lulu33
lulu33

Reputation: 327

Resolved it with checking for pathname

const PrivateRoute = ({
  component: Component,
  exact,
  path,
}: RouteProps): JSX.Element => {
  if (!Component) return <div>ERROR</div>;
  const classes = useStyles();
  const auth = useSelector((state: RootState) => state.auth);
  return (
    <Route
      path={path}
      exact={exact}
      render={(props) => (auth.loading ? (
        <Backdrop className={classes.backdrop} open>
          <CircularProgress color="inherit" />
        </Backdrop>
      ) : auth.isAuthenticated ? (
        <Component {...props} />
      ) : (props.location.pathname !== '/login') && (
      <Redirect to={{
        pathname: '/login',
        state: { from: props.location },
      }}
      />
      ))}
    />
  );
};

Upvotes: 1

Related Questions