简体   繁体   中英

React private route component renders twice

Im writing an React/firebase app and I'm trying to get some private routes to work. Im using {useAuthState} from react-firebase-hooks/auth to help me authenticate.

App:

let App = () => {
  const [user] = useAuthState(auth);
  return (
   <Navbar
      ...
      <a href="/user" />user</a>
      ...
   />
   <Router>
       <div className='main-content'>
       <Route path='/auth/signin' component={Login} />
       <ProtectedRoute path='/user' component={UserHome} 
        isAuth={user} />
   ..
  };

Protected route:

const ProtectedRoute = ({ component: Component, isAuth, ...rest }) => {
  return (
    <Route
      {...rest}
      render={(props) =>
        isAuth ? (
          <Component {...props} />
        ) : (
          <Redirect
            to={{ pathname: "/user/signin", state: { from: props.location } }}
          />
        )
      }
    />
  );
};

export default ProtectedRoute;

But react keeps rendering the components twice, and at the first render the props are null which triggers the protected route to Redirect. But on second render the props are all there but then it's to late and the redirect has occurred.

Is it possible to wait for all the props to load before render or redirect? Or is there any other way to solve this?

Best regards

Since useAuthState may take a while to fetch the information of the user, you should use the loading prop that it provides to wait for it to finish:

let App = () => {
  const [user, loading, error] = useAuthState(auth);
  if (loading) {
    return (
      <div>
        <p>Initialising User...</p>
      </div>
    );
  }
  if (error) {
    return (
      <div>
        <p>Error: {error}</p>
      </div>
    );
  }
  return (
    <Navbar
      ...
      <a href="/user" />user</a>
      ...
    />
    <Router>
       <div className='main-content'>
       <Route path='/auth/signin' component={Login} />
       <ProtectedRoute path='/user' component={UserHome} 
        isAuth={user} />
    ..
  };

You can read more here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM