2개 답변
- 최신
- 최다 투표
- 가장 많은 댓글
0
Hello MD,
To redirect a user after they log in using the AWS Amplify Authenticator, you can use the onStateChange
prop to listen for changes in the authentication state and then conditionally redirect the user to the desired location (e.g., /dashboard
). Here's how you can achieve this:
- Import the necessary components and libraries:
import React, { useEffect, useState } from "react"; import { Authenticator } from "@aws-amplify/ui-react"; import { Auth } from "aws-amplify"; // Import Auth from AWS Amplify import "@aws-amplify/ui-react/styles.css"; import Wrapper from "../../../element-components/base-components/Wrapper"; import { useHistory } from "react-router-dom"; // Import useHistory from react-router-dom
- Create your functional component:
export const AmplifyHostedUI: React.FC = () => { const component = { SignIn: { Header() { return <div className="flex text-xl font-bold pb-4">Log-In</div>; }, }, }; const history = useHistory(); // Create a history object to manage navigation // State to track the current authentication state const [authState, setAuthState] = useState<string | undefined>(undefined); useEffect(() => { // Add an event listener to handle changes in authentication state const listener = async (state: string, data: any) => { if (state === "signedin") { // Redirect the user to the /dashboard route upon successful sign-in history.push("/dashboard"); } setAuthState(state); }; // Subscribe to the event Auth.currentAuthenticatedUser() .then((user) => { setAuthState("signedin"); }) .catch((err) => { setAuthState("signIn"); }); const subscription = Auth.subscribe(listener); return () => { // Unsubscribe from the event when the component is unmounted subscription.unsubscribe(); }; }, [history]); return ( <Wrapper> <div className="flex h-fit w-fit"> <Authenticator hideSignUp components={component} authState={authState}></Authenticator> </div> </Wrapper> ); }; export default AmplifyHostedUI;
In this code:
- We import the
useHistory
hook fromreact-router-dom
to manage navigation. - We create a
history
object to interact with the router. - We use the
useEffect
hook to add an event listener that listens for changes in the authentication state. - When the state changes to
"signedin"
(i.e., the user successfully signs in), we usehistory.push("/dashboard")
to redirect the user to the/dashboard
route. - The
authState
prop is set to the current authentication state to display the appropriate UI components.
With this setup, after the user successfully logs in, they will be redirected to the /dashboard
route.
답변함 8달 전
0
Hi guys,
I solved using useNavigate (React Router >= 6 ) instead of useHistory(). And Amplify Hub instead of Auth.subscribe().
Tested with
- React 18.2.0
- react-router-dom 6.10.0
- @aws-amplify/ui-react 5.1.1
//
// index.tsx
//
import React from "react";
import ReactDOM from "react-dom/client";
import { Amplify } from "aws-amplify";
import { HashRouter as Router } from "react-router-dom";
import App from "./App";
import awsconfig from "./aws-exports";
import "@aws-amplify/ui-react/styles.css";
Amplify.configure(awsconfig);
const root = ReactDOM.createRoot(
document.getElementById("root") as HTMLElement,
);
root.render(
<React.StrictMode>
<Router>
<App />
</Router>
</React.StrictMode>,
);
//
// App.tsx
//
import { FC, useEffect } from "react";
import { Authenticator } from "@aws-amplify/ui-react";
import { Hub } from "aws-amplify";
import { Link, Routes, Route, useNavigate } from "react-router-dom";
const App: FC = () => {
const navigate = useNavigate();
useEffect(() => {
Hub.listen("auth", (data) => {
if (data?.payload?.event === "signIn") {
navigate("/protected");
}
});
}, []);
return (
<Authenticator>
{({ signOut, user }) => {
return (
<>
<Link to="/protected/about">About</Link>
<button onClick={signOut}>Sign out</button>
<Routes>
<Route
element={<h1>Protected about</h1>}
path={"/protected/about"}
/>
<Route element={<h1>Protected</h1>} path={"/protected"} />
</Routes>
</>
);
}}
</Authenticator>
);
};
export default App;
Hope this could help
답변함 7달 전
관련 콘텐츠
- AWS 공식업데이트됨 2년 전
The above code not working ,
useHistory
not available onreact-router-dom
also Auth class does not havesubscribe
method