0

I'm currently struggling with how to redirect to the homepage when a user clicks a button that will sign them up for an account: My Current set-up is like this

function Application() {
    const user = useContext(UserContext);
    return (
        user ?
            <Router>
                <LandingScreen path="landingscreen"/>
             </Router>

            :
            <Router>
                <SignUp path="signUp" />
                <SignIn path="/" />
            </Router>

    );
}
export default Application;
const SignIn = () => {

    const [email, setEmail] = useState('');
    const [password, setPassword] = useState('');
    const [error, setError] = useState(null);

    const signInWithEmailAndPasswordHandler = (event,email, password) => {
        event.preventDefault();
        auth.signInWithEmailAndPassword(email, password).catch(error => {
            setError("Error signing in with password and email!");
            console.error("Error signing in with password and email", error);
        });
    };

How would I add a function signInWithEmailAndPasswordHandler so that when it is called, it will redirect the user to /landingscreen? I've read the reach documentation but I'm new to JSX and struggling to implement this.

Luke Egan
  • 81
  • 6

2 Answers2

0
import { useHistory } from 'react-router-dom';

const SignIn = () => {

    const [email, setEmail] = useState('');
    const [password, setPassword] = useState('');
    const [error, setError] = useState(null);
    const history = useHistory(); // Add this from redux-form

    const signInWithEmailAndPasswordHandler = (event,email, password) => {
        event.preventDefault();
        auth.signInWithEmailAndPassword(email, password).catch(error => {
            setError("Error signing in with password and email!");
            console.error("Error signing in with password and email", error);
        })
        // Add this (if you want it call only if not catched error, place it before .catch
        .then(() => {   
            history.push('/landingscreen');
        });
    };
Tonoslav
  • 517
  • 2
  • 6
  • 20
0

You can use react-router-dom hooks and call history.push('url')

import { useHistory } from "react-router-dom";

const SignIn = () => {
    const history = useHistory()
    const [email, setEmail] = useState('');
    const [password, setPassword] = useState('');
    const [error, setError] = useState(null);

    const signInWithEmailAndPasswordHandler = (event,email, password) => {
        event.preventDefault();
        auth.signInWithEmailAndPassword(email, password)
        .then(() => {
          // Logged in successfully
          history.push('/landingscreen');
        })
        .catch(error => {
            setError("Error signing in with password and email!");
            console.error("Error signing in with password and email", error);
        })
    };
Zohaib Ijaz
  • 21,926
  • 7
  • 38
  • 60