简体   繁体   中英

how to redirect after login with firebase

I used the signInWithEmailAndPassword function from firebase to signIn and i used history.push('/') to redirect to home page after authentication. My problem is when i click on sign in button it doesn't work from the first click , it work only from the second click.
this is an image of the result from first click

//login.js

import React, { useState} from 'react';
import { useHistory } from "react-router-dom";
import { auth } from "../firebase";

export default function Login(){

    const classes = useStyles();
    const history = useHistory()
    const [email, setEmail] = useState('')
    const [password, setPassword] = useState('')
  
    const signIn = (e) => {
      e.preventDefault();

      auth.signInWithEmailAndPassword(email, password)
      
          .then(() => {   
            history.push('/')           
                          
          })
          .catch(error => alert(error.message))
  }


    return(

    <div className="container__login">
      <img src={Logo} className={classes.logo} alt="sicilia mia logo" />

     <Container component="main" maxWidth="xs" className={classes.container}>
      <CssBaseline />
      <div className={classes.paper}>
        <Avatar className={classes.avatar}>
          <LockOutlinedIcon />
        </Avatar>
        <Typography component="h1" variant="h5">
          Sign in
        </Typography>
        <Divider  variant="middle"/>
        <form onSubmit={signIn} noValidate>
          <TextField
            variant="outlined"
            margin="normal"
            required
            fullWidth
            id="email"
            label="Email Address"
            type="email"
            value={email} 
            onChange={e => setEmail(e.target.value)}
            autoComplete="email"
            autoFocus
          />
          <TextField
            variant="outlined"
            margin="normal"
            required
            fullWidth
            name="password"
            label="Password"
            type="password"
            value={password} 
            onChange={e => setPassword(e.target.value)}
            id="password"
            autoComplete="current-password"
          />
         
          <Button
            type="submit"
            fullWidth
            variant="contained"
            color="primary"
            className={classes.submit}
            
          >
            Sign In
          </Button>
         
        </form>
      </div>
      
    </Container>

        
    
        <img className={classes.circleImg} src={Circle} alt="circle design" ></img>


        </div>
    )
}
//App.js

function App() {
  return (
    <div className="App">
        <AuthProvider>
       
           <Router>
    
           <Route exact path="/login" component={Login} />
           <PrivateRoute exact path="/" component={Guidelines}/>
 
          </Router>
        </AuthProvider>
    </div>
  );
}

export default App;

It takes firebase some time to verify the authenticated user, add an onAuthStateChange in a useEffect in App.js, and when the user is verified then set the authenticated user to the local state. And then only render the private route if the user exists.

const [user, setUser] = useState(null);
useEffect(() => {
   
    const unsubscribe = auth.onAuthStateChanged(async (userAuth) => {
      if (userAuth) {
        // User logged in
        setUser(userAuth);
      } else {
        // User logged out
        setUser(null);
      }
    });

    return unsubscribe;
  }, []);

  return (
    <div className="app">
      <Router>
        <Switch>   
          <Route path="/login">
            <Login/>
          </Route>
          {user && <ProtectedRoute exact path="/" component={Guidelines} />}
        </Switch>
      </Router>
    </div>
  );
}

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM