How to perform authentication with React hooks and react-router

百般思念 提交于 2021-01-02 07:56:16

问题


I am trying to authenticate user on each route change with react-router-dom and react hooks. The idea is that each time user navigates to a route the system makes an api call and authenticate the user. I need to achieve this because I use react-redux, and on each window reload the redux state is not persisted. So i need to set the isLoggedNow prop to true again:

const PrivateRoute = ({
  component: Component,
  checkOnEachRoute: checkReq,
  isUserLogged,
  ...rest
}) => {
  const [isLoggedNow, setLogged] = useState(isUserLogged);
  useEffect(
    () => {
      const fetchStatus = async () => {
        try {
          await selectisUserLogged();
          setLogged(true);
        } catch (error) {
          console.log(error);
        }
      };
      fetchStatus();
    },
    [isUserLogged],
  );
  return (
    <Route
      {...rest}
      render={props =>
        isLoggedNow ? (
          <div>
            <Component {...props} />
          </div>
        ) : (
          <Redirect
            to={{
              pathname: '/login',
            }}
          />
        )
      }
    />
  );
};

I then would use the above PrivateRoute like this:

function App(props) {
  return (
    <div>
      <Switch location={props.location}>
        <Route exact path="/login" component={Login} />
        <PrivateRoute exact path="/sidebar" component={Sidebar} />
      </Switch>
    </div>
  );
}

First the isUserLogged is true, but after window reload I get an error Warning: Can't perform a React state update on an unmounted component. So how can I achieve this, so on each window reload I authenticate the user? I am looking for some kind of componentWillMount.


回答1:


Something like this works (where isUserLogged is a prop from redux):

function PrivateRoute({ component: Component, isUserLogged, ...rest }) {
  const [isLoading, setLoading] = useState(true);
  const [isAuthenticated, setAuth] = useState(false);
  useEffect(() => {
    const fetchLogged = async () => {
      try {
        setLoading(true);
        const url = new URL(fetchUrl);
        const fetchedUrl = await fetchApi(url);
        setAuth(fetchedUrl.body.isAllowed);
        setLoading(false);
      } catch (error) {
        setLoading(false);
      }
    };
    fetchLogged();
  }, []);
  return (
    <Route
      {...rest}
      render={props =>
        // eslint-disable-next-line no-nested-ternary
        isUserLogged || isAuthenticated ? (
          <Component {...props} />
        ) : isLoading ? (
          <Spin size="large" />
        ) : (
          <Redirect
            to={{
              pathname: '/login',
            }}
          />
        )
      }
    />
  );
}


来源:https://stackoverflow.com/questions/55358875/how-to-perform-authentication-with-react-hooks-and-react-router

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!