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?
2
Answers
The
user
variable is being shaddowed by youronSubmit
function parameter:It doesn’t look like
user
is passed to that function, so it would beundefined
.Simply remove it from the params, and use
user
from the outer scope.You are overwriting your user in the function. There should not be shadow variables in the code (different context same variable name different value)