How to use Auth api from AWS amplify without refreshing and redirecting application to different URL?

276 views Asked by At
export default function Home() {
  const [user, setUser] = useState("");

  useEffect(() => {
    Auth.currentAuthenticatedUser().then((user) => {
      setUser(user.username);
    });

    Hub.listen("auth", (data) => {
      switch (data.payload.event) {
        case "signIn":
          return setUser(data.payload.data.username);
        case "signOut":
          return setUser("");
      }
    });
  }, [setUser]);

  const handleGoogleLogin = () => {
    Auth.federatedSignIn({
      provider: CognitoHostedUIIdentityProvider.Google,
    });
  };

  const handleSignOut = () => {
    Auth.signOut({
      global: true,
    }).then(() => {});
  };

  return (
    <>
      {!user && <button onClick={handleGoogleLogin}>Google</button>}
      {user && (
        <button onClick={handleSignOut}>LogOut</button>
      )}
      <h1>Hello {user}, this is my app</h1>
    </>
  );
}

In this react component, i am using the AWS api to sign in with google and to sign out when users is logged. The problem is that Auth.federatedSignIn use the same tab of my application to open google login form, and Auth.signOut refresh my application. How can I use this API only relying on Hub.listen to send auth events to my app?

0

There are 0 answers