Home > Software engineering >  undefined user id when trying to submit a form to firebase db
undefined user id when trying to submit a form to firebase db

Time:08-27

I'm trying to create a new collection of a parents children based off their user id, but when I try I'm getting undefined:

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>
    );
}

Outside of my onSubmit function I can print the user.uid to the console, but inside of it returns undefined.

What am I doing wrong?

CodePudding user response:

The user variable is being shaddowed by your onSubmit function parameter:

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

It doesn't look like user is passed to that function, so it would be undefined.

Simply remove it from the params, and use user from the outer scope.

const onSubmit = async () => {

CodePudding user response:

You are overwriting your user in the function. There should not be shadow variables in the code (different context same variable name different value)

// 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',
            });
    
        }
    }
  • Related