skip to Main Content

I’m trying to do a login with laravel react, so when I receive jwt from server I wanna redirect to my main page, but I continue to stay on the same page

import { Route, BrowserRouter as Redirect } from 'react-router-dom';


const Login = () => {
    const [email, setEmail] = useState("");
    const [password, setPassword] = useState("");
    const [jwt, setJwt] = useState("");

    const login = async (e) => {
        e.preventDefault();
        await axios.post("/login", {
            email: email,
            password: password
        }).then((response) => {
            console.log(response)
            if (response.data[0] === "credenziali errate") {
                console.log('credenziali errate')
            } else if (response.data.token) {
                setJwt(response.data.token);
                return (<Route>
                    <Redirect to="/" />
                </Route>)

            }
        });
        setEmail("")
        setPassword("")
    }

    return (
        <div>
            <input type="email" value={email} onChange={(e) => setEmail(e.target.value)} name="" id="" required/>
            <input type="password" value={password} onChange={(e) => setPassword(e.target.value)} name="" id="" required/>
            <button type="submit" onClick={login}>Login</button>
        </div>
    );
}

2

Answers


  1. You’re returning a React Element (…) within a function / promise.

    Instead of returning that, call redirect('/') see: https://reactrouter.com/en/main/fetch/redirect

    Login or Signup to reply.
  2. Returning JSX only has an effect when done synchronously, directly in the body of the component. Use the useNavigate hook instead.

    import { useNavigate } from 'react-router-dom';
    // inside component:
    const navigate = useNavigate();
    // after axios request completes:
    navigate('/'); // go to home page
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search