Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I redirect to auth0 without clicking on the Log In button in react using the new auth0-spa.js?

I was working with the new auth0-spa and followed its tutorial to implement the auth0 SDK given by auth0 here. I want to automatically redirect to the auth0 login page instead of a page that gives a button saying Log In. Can anyone help me? Here is my code

import PrivateRoute from "./PrivateRoute";
import React,{useState} from "react";
import { useAuth0 } from "../react-auth0-spa";
import {BrowserRouter, HashRouter, Link, Route, Router, Switch} from "react-router-dom";
import DefaultLayout from "../containers/DefaultLayout";
import history from "../utils/history";
const NavBar = () => {
const { isAuthenticated, loginWithRedirect, logout } = useAuth0();

return (

<div>
  {!isAuthenticated && (
    <button id="button" onClick={() => loginWithRedirect({})}>Log in</button>
  )}

  {isAuthenticated && (
    <HashRouter history = {history}>
      <Switch>
        <PrivateRoute path="/" component={DefaultLayout}/>
      </Switch>
    </HashRouter>
  )}
</div>
);
};

export default NavBar;
like image 536
Aditya Jadhav Avatar asked Dec 05 '25 15:12

Aditya Jadhav


1 Answers

This is what I did:

const App: React.FC<{}> = () => {

    const { isLoading, loginWithRedirect, user } = useAuth0();

    useEffect(() => {
      (async function login() {
        if (!isLoading && !user) {
          await loginWithRedirect();
        }
      })();
    }, [isLoading]);

    return (
      <React.Fragment>
        {/* your code */}
      </React.Fragment>
    )
  }
like image 123
Brahim Bouaboud Avatar answered Dec 07 '25 11:12

Brahim Bouaboud