繁体   English   中英

尝试向 firebase db 提交表单时未定义的用户 ID

[英]undefined user id when trying to submit a form to firebase db

我正在尝试根据他们的用户 ID 创建一个新的父子集合,但是当我尝试时,我变得不确定:

import React from "react";
import { useForm } from "react-hook-form";
import { db, auth } from '../firebase/firebaseInit'
import {useAuth} from '../components/AuthContextProvider'
import { collection, setDoc, doc } from '@firebase/firestore'
import Logout from '../components/Logout'

type Inputs = {
  example: string,
  exampleRequired: string,
};

export default function LoggedIn() {
    const { user  } = useAuth()
    const { register, handleSubmit, watch, formState: { errors } } = useForm<Inputs>();
    console.log(user.uid, 'this uid is not undefined')
    // add their kid to the kids collection
    const onSubmit = async (user: any) => {
        if (user) {
            console.log(user.uid, 'this uid is undefined')
            const userRef = doc(db, `kids/${user.uid}`);
            await setDoc(userRef, {
                parent: user.displayName,
                email: user.email,
                uid: user.uid,
                name: 'Charlie',
            });
    
        }
    }

    return (
    <div>
        <Logout />
        <form onSubmit={handleSubmit(onSubmit)}>
        <input type="submit" />
    </form>
    </div>
    );
}

在我的onSubmit function 之外,我可以将user.uid打印到控制台,但在其中返回未定义。

我究竟做错了什么?

您的onSubmit function 参数隐藏了user变量:

const onSubmit = async (user: any) => {

看起来user没有传递给 function,所以它是undefined

只需将其从参数中删除,并使用外部 scope 中的user

const onSubmit = async () => {

您正在覆盖 function 中的用户。 代码中不应该有影子变量(不同的上下文相同的变量名不同的值)

// your user
    const { user  } = useAuth()
    const { register, handleSubmit, watch, formState: { errors } } = useForm<Inputs>();
    console.log(user.uid, 'this uid is not undefined')
    // add their kid to the kids collection
// other user (the user which is passed to the callback)
    const onSubmit = async (user: any) => {
        if (user) {
            console.log(user.uid, 'this uid is undefined')
            const userRef = doc(db, `kids/${user.uid}`);
            await setDoc(userRef, {
                parent: user.displayName,
                email: user.email,
                uid: user.uid,
                name: 'Charlie',
            });
    
        }
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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