【问题标题】:firebase `onAuthStateChanged` function returns null each timefirebase `onAuthStateChanged` 函数每次都返回 null
【发布时间】: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


    【解决方案1】:

    用户的创建不同于使用的认证。

    在创建用户时,您将存储新的用户凭据(电子邮件/密码),而在对用户进行身份验证时,您会将提供的凭据与存储的凭据进行匹配。

    监听器onAuthStateChanged 似乎安装得很好,但您没有进行任何身份验证,因此它会提交一个新值:已验证的user

    成功创建用户并验证其帐户后,您可以触发登录请求,如下所示:

    const handleAuth = (e : React.FormEvent<HTMLFormElement>) => {
        // ...
        fetchData(path, 'POST', {
            email : email.current.value,
            password : password.current.value
        }).then(() => auth.signInWithEmailAndPassword(email.current.value, password.current.value))
    }
    

    然后注册的onAuthStateChanged监听器将被正确的用户身份触发。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-10-07
      • 1970-01-01
      • 1970-01-01
      • 2016-05-22
      • 1970-01-01
      • 1970-01-01
      • 2022-09-27
      • 1970-01-01
      相关资源
      最近更新 更多