Friday, February 23, 2024
 Popular · Latest · Hot · Upcoming
18
rated 0 times [  24] [ 6]  / answers: 1 / hits: 6578  / 3 Years ago, mon, march 8, 2021, 12:00:00

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.


More From » reactjs

 Answers
3

This code is working.


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 { isAuthenticated, loginWithRedirect } = useAuth0();
const history = useHistory();

React.useEffect(() => {
async function checkUser() {
if (isAuthenticated) {
await history.push("/explore");
} else {
loginWithRedirect();
}
}

checkUser(); // called async checkUser()
}, [isAuthenticated, loginWithRedirect]); // added loginWithRedirect

return <SplashScreen />;
}

export default LoginView;

[#1679] Tuesday, March 2, 2021, 3 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
jamila

Total Points: 490
Total Questions: 94
Total Answers: 94

Location: Lebanon
Member since Sun, Aug 2, 2020
4 Years ago
;