You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Firebase v9+React注册用户时如何上传自定义UID关联文档?

React + Firebase 9 注册时无法创建用户额外数据文档

我用React和Firebase 9开发,默认用户字段不够用,想在注册时把额外数据(比如displayName)存入Firestore,但现在只有用户注册成功,Firestore里的users集合没生成对应文档。

以下是我的代码:

import { useState } from "react"
import { auth, db } from "../Authentication/firebaseConfig"
import { createUserWithEmailAndPassword } from "firebase/auth"
import {
    collection,
    setDoc,
    addDoc,doc
} from "firebase/firestore";


export const useSignup = () => {
    const [error, setError] = useState(null)

    const signup = async (email, password, displayName) => {
        setError(null)

        const current_user = await createUserWithEmailAndPassword(auth, email, password, displayName);
        const uid = current_user.user.uid;
        await addDoc(collection(db, "users"), {
            uid: uid,
            displayName,
            email,
        })
          .then((res) => {
            console.log('user signed up:', res.user)
        })
    .catch((err) => {
        setError(err.message)
    })
    }
    return { error, signup }
}

问题分析与修复方案

核心问题:

  1. 参数错误:createUserWithEmailAndPassword只接受auth、email、password三个参数,你传的第四个displayName是无效的,不会被处理。
  2. 错误混用异步语法:async函数里同时用了await和then/catch,逻辑混乱,且addDoc返回的是文档引用,没有res.user属性,这会触发隐藏错误但没被正确暴露。
  3. 错误处理不完整:createUserWithEmailAndPassword的await没有包裹在try/catch里,万一注册失败会直接抛出错误,不会执行后续的Firestore写入逻辑。

修正后的代码:

import { useState } from "react"
import { auth, db } from "../Authentication/firebaseConfig"
import { createUserWithEmailAndPassword, updateProfile } from "firebase/auth"
import { collection, addDoc } from "firebase/firestore";

export const useSignup = () => {
    const [error, setError] = useState(null)

    const signup = async (email, password, displayName) => {
        setError(null)
        try {
            // 1. 创建基础用户
            const userCredential = await createUserWithEmailAndPassword(auth, email, password);
            const user = userCredential.user;

            // 2. 可选:更新Auth用户的displayName(如果需要在Auth系统中存储该字段)
            await updateProfile(user, { displayName });

            // 3. 写入Firestore存储额外用户数据
            await addDoc(collection(db, "users"), {
                uid: user.uid,
                displayName,
                email,
                createdAt: new Date() // 可选:添加创建时间,方便后续查询
            });

            console.log('用户注册成功,文档已创建:', user);
        } catch (err) {
            setError(err.message);
            console.error('注册失败详情:', err);
        }
    }

    return { error, signup }
}

额外说明:

  • 用try/catch统一处理异步错误,避免语法混用导致的逻辑漏洞
  • 如果不需要在Firebase Auth系统中存储displayName,可以去掉updateProfile步骤
  • 添加createdAt字段是常见的业务需求,可根据实际情况取舍

内容的提问来源于stack exchange,提问作者Danial

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.26 00:24:32