In React app, I was going to implement Auth0 login like the following. When the user accesses the /login
, it will check if the user is authenticated.
Here is the code.
import React from 'react';
import { useHistory } from "react-router-dom";
import { useAuth0 } from "@auth0/auth0-react";
import SplashScreen from "src/components/SplashScreen";
const LoginView = () => {
const { loginWithRedirect, isAuthenticated } = useAuth0();
const history = useHistory();
React.useEffect(() => {
if (isAuthenticated) {
history.push("/explore");
} else {
loginWithRedirect();
}
}, [isAuthenticated])
return <SplashScreen />;
};
export default LoginView;
But when I log in from the Auth0 login page, I am redirected to the /login
page of the React app, and it falls in looping indefinitely. I tried to log out the isAuthenticated
value on the console like in the above code, but it is false
even though I logged in on the Auth0 authentication page correctly.
Please let me know how I can solve this issue. Thanks.
This code is working.
import React from 'react';
import axios from 'axios';
import { useHistory } from "react-router-dom";
import { useAuth0 } from "@auth0/auth0-react";
import SplashScreen from "src/components/SplashScreen";
const LoginView = () => {
const { isAuthenticated, loginWithRedirect } = useAuth0();
const history = useHistory();
React.useEffect(() => {
async function checkUser() {
if (isAuthenticated) {
await history.push("/explore");
} else {
loginWithRedirect();
}
}
checkUser();
}, [isAuthenticated, loginWithRedirect]);
return (
<SplashScreen />
);
}
export default LoginView;
I used the below pattern source: https://thinkster.io/tutorials/auth0-react-login-and-user-profile/protect-the-profile-route
const { loading, isAuthenticated, loginWithRedirect } = useAuth0();
useEffect(() => {
if (loading || isAuthenticated) {
return;
}
const fn = async () => {
await loginWithRedirect({
appState: { targetUrl: path }
});
};
fn();
}, [loading, isAuthenticated, loginWithRedirect, path]);
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.