简体   繁体   中英

PrivateRoute functional component using aws-amplify as authentication

I'm trying to create a functional component equivalent of the following PrivateRoute class component (source code here ):

import React, { useState, useEffect } from "react";
import { Route, Redirect, withRouter, useHistory } from "react-router-dom";
import { Auth } from "aws-amplify";

class PrivateRoute extends React.Component {
  state = {
    loaded: false,
    isAuthenticated: false
  };
  componentDidMount() {
    this.authenticate();
    this.unlisten = this.props.history.listen(() => {
      Auth.currentAuthenticatedUser()
        .then(user => console.log("user: ", user))
        .catch(() => {
          if (this.state.isAuthenticated)
            this.setState({ isAuthenticated: false });
        });
    });
  }
  componentWillUnmount() {
    this.unlisten();
  }
  authenticate() {
    Auth.currentAuthenticatedUser()
      .then(() => {
        this.setState({ loaded: true, isAuthenticated: true });
      })
      .catch(() => this.props.history.push("/auth"));
  }
  render() {
    const { component: Component, ...rest } = this.props;
    const { loaded, isAuthenticated } = this.state;
    if (!loaded) return null;
    return (
      <Route
        {...rest}
        render={props => {
          return isAuthenticated ? (
            <Component {...props} />
          ) : (
            <Redirect
              to={{
                pathname: "/auth"
              }}
            />
          );
        }}
      />
    );
  }
}

export default withRouter(PrivateRoute);

The above code works in my application when I use it like so:

<PrivateRoute
  exact
  path={urls.homepage}
  component={Homepage}
/>

My attempt at a converting the above class component into a functional component is the following:

import React, { useState, useEffect } from "react";
import { Route, Redirect, useHistory } from "react-router-dom";
import { Auth } from "aws-amplify";

const PrivateRoute = ({ component: Component, ...rest }) => {
  const [isLoaded, setIsLoaded] = useState(false);
  const [isAuthenticated, setIsAuthenticated] = useState(false);
  let history = useHistory();

  useEffect(() => {
    Auth.currentAuthenticatedUser()
      .then(() => {
        setIsLoaded(true);
        setIsAuthenticated(true);
      })
      .catch(() => history.push("/auth"));

    return () =>
      history.listen(() => {
        Auth.currentAuthenticatedUser()
          .then(user => console.log("user: ", user))
          .catch(() => {
            if (isAuthenticated) setIsAuthenticated(false);
          });
      });
  }, [history, isAuthenticated]);

  if (!isLoaded) return null;

  return (
    <Route
      {...rest}
      render={props => {
        return isAuthenticated ? (
          <Component {...props} />
        ) : (
          <Redirect
            to={{
              pathname: "/auth"
            }}
          />
        );
      }}
    />
  );
};

export default PrivateRoute;

But when using my functional component in the same way, I keep getting the following error:

Warning: Can't perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in a useEffect cleanup function

It always redirects me to /auth, regardless of whether I am logged in or not. What am I doing wrong? Any help is much appreciated!

I think you are missing your unmount, the return in the useEffect should be your unlisten which is the unmount. Also, I removed useHistory and pulled history from the props and used withRouter

Try this

import React, { useState, useEffect } from "react";
import { Route, Redirect, withRouter } from "react-router-dom";
import { Auth } from "aws-amplify";

const PrivateRoute = ({ component: Component, history, ...rest }) => {
  const [isLoaded, setIsLoaded] = useState(false);
  const [isAuthenticated, setIsAuthenticated] = useState(false);

  useEffect(() => {
    Auth.currentAuthenticatedUser()
      .then(() => {
        setIsLoaded(true);
        setIsAuthenticated(true);
      })
      .catch(() => history.push("/auth"));
    
    const unlisten = history.listen(() => {
      Auth.currentAuthenticatedUser()
        .then(user => console.log("user: ", user))
        .catch(() => {
          if (isAuthenticated) setIsAuthenticated(false);
        });
    });

    return unlisten();
  }, [history, isAuthenticated]);

  if (!isLoaded) return null;

  return (
    <Route
      {...rest}
      render={props => {
        return isAuthenticated ? (
          <Component {...props} />
        ) : (
          <Redirect
            to={{
              pathname: "/auth"
            }}
          />
        );
      }}
    />
  );
};

export default withRouter(PrivateRoute);

Try this out:

useEffect(() => {
  async function CheckAuth() {
    await Auth.currentAuthenticatedUser()
      .then((user) => {
        setIsLoaded(true);
        setIsAuthenticated(true);
      })
    .catch(() => history.push("/auth"));
  }
  CheckAuth();
}, []);

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