【发布时间】:2021-11-12 03:47:15
【问题描述】:
当我在注册后调用handleAuth 函数时,已经创建了一个用户(我可以看到他被添加到了firebase 身份验证网络),但是onAuthStateChanged 记录为空。
在用户成功登录后,我在 useEffect 中调用它。其中的 console.log(data) 从服务器响应数据中返回用户的令牌。
为什么onAuthStateChanged 返回 null?
import 'bootstrap/dist/css/bootstrap.min.css';
import 'bootstrap-icons/font/bootstrap-icons.css';
import { useEffect, useRef, useState } from 'react';
import useFetch from '../hooks/useFetch';
import { useLocation } from 'react-router';
import { auth } from '../config/firebaseConfig';
export default function Authenticate() : JSX.Element {
const url = useLocation().pathname;
const { fetchData, data, error, loading } = useFetch();
const email = useRef() as React.MutableRefObject<HTMLInputElement>;
const password = useRef() as React.MutableRefObject<HTMLInputElement>;
const [show, setShow] = useState(false);
const handleAuth = (e : React.FormEvent<HTMLFormElement>) => {
e.preventDefault();
const path = (e.nativeEvent as any).submitter.name === 'login' ?
`${url}/login/email` : `${url}/register`;
fetchData(path, 'POST', {
email : email.current.value,
password : password.current.value
});
}
useEffect(() => {
if(data)
{
console.log(data)
auth.onAuthStateChanged(user => console.log(user));
}
}, [data])
return (
<div className="d-flex justify-content-center align-items-center vh-100 bg-white">
<div className="p-5 border border-2 border-success">
<h1 className="fw-light fs-2 text-center">Authenticate</h1>
<br/>
<form onSubmit={e => handleAuth(e)}>
<div className="form-group">
<label>Email</label>
<div className="input-group">
<span className="input-group-text bi bi-person-circle"></span>
<input type="email" ref={email} className="form-control" placeholder="boomer@bommer.com" required/>
</div>
</div>
<div className="form-group">
<label>Password</label>
<div className="input-group">
<span className="input-group-text bi bi-key-fill"/>
<input type={show ? "text" : "password"} className="form-control" ref={password} placeholder="enter your password" required/>
<button type="button" className={`input-group-text text-decoration-none bi bi-${show ? 'eye-fill' : 'eye-slash-fill' }`} onClick={() => setShow(!show)}/>
</div>
</div>
<br/>
{ error && <p className={`alert alert-danger p-1 text-center`} role="alert">{error}</p> }
<div className="d-flex justify-content-between">
<button type="submit" name="register" className="btn btn-primary" disabled={loading}>Register</button>
<button type="submit" name="login" className="btn btn-primary" disabled={loading}>Login</button>
</div>
</form>
</div>
</div>
);
}
【问题讨论】:
标签: reactjs firebase firebase-authentication