Issue
I am quite new to React JS and was trying to make an app. However whenever typing something in a textbook, the whole app seems to freeze and then stop working.
import React, { useState } from 'react'
import { auth } from './firebase';
import styles from '../static/SignIn.module.css';
import { Link, useNavigate } from "react-router-dom";
import {
// createUserWithEmailAndPassword,
signInWithEmailAndPassword,
onAuthStateChanged,
// signOut,
} from "firebase/auth";
export default function SignIn(){
const [user, setUser] = useState({});
const history = useNavigate();
onAuthStateChanged(auth, (currentUser) => {
setUser(currentUser);
});
// const goBack = () => {
// history.push('/')
// };
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const signIn = async() => {
try {
const user = await signInWithEmailAndPassword(
auth,
email,
password
);
history.push('/home')
console.log(user);
} catch (error) {
console.log(error)
if (password.length < 6){
alert('Password should be at least 6 characters!')
}
}
}
return(
<div className={styles.main}>
<div className={styles.center}>
<h1>Login</h1>
<div className={styles.form}>
<div className={styles.txt_field}>
<input type="text" id='text' name='text' value={email} onChange={e => setEmail(e.currentTarget.value)} required/>
<span></span>
<label>Email ID</label>
</div>
<div className={styles.txt_field}>
<input type="password" id='password' name='password' value={password} onChange={e => setPassword(e.currentTarget.value)} required/>
<span></span>
<label>Password</label>
</div>
<input type="submit" value="Login" onClick={signIn}/>
<div className={styles.signup_link}>
Not a member? <Link to="/signup">Signup</Link>
</div>
</div>
</div>
</div>
)
}
Any help would be appreciated because this is stopping me from progressing further, as I need to rerun the app using npm start
in order to make it work.
Solution
I think your issue is that on every render of the SignIn
component you call the onAuthStateChanged
listener. I have never used this but my guess is that it would need to be called only once, when the component mounts.
So you could do something like this instead:
export default function SignIn(){
const [user, setUser] = useState({});
const history = useNavigate();
React.useEffect(() => {
onAuthStateChanged(auth, (currentUser) => setUser(currentUser))
// Notice the empty dependency array, there to make sure the effect is only run once when the component mounts
}, [])
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
// ...
}
Answered By - Alarid
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.