I am trying to register a user. After successfully using createUserWithEmailAndPassword
and then uploading an image to its auth details, I want to create a users collection to store all user info. This is my code:
//CREATE USER ACCOUNT
const user = await createUserWithEmailAndPassword(
auth,
data.Email,
data.Password
);
//UPLOAD IMAGE
const storageRef = ref(storage, `${data.Email}`);
if (profileIcon != undefined) {
const uploadTask = uploadBytesResumable(storageRef, profileIcon);
uploadTask.on(
"state_changed",
(error) => {
setError(true);
console.log(error);
},
() => {
getDownloadURL(uploadTask.snapshot.ref).then(async (downloadURL) => {
await updateProfile(user.user, {
displayName: `${data.FirstName} ${data.LastName}`,
photoURL: downloadURL,
});
await setDoc(doc(db, "users", user.user.uid), {
uid: user.user.uid,
displayName: `${data.FirstName} ${data.LastName}`,
firstName: data.FirstName,
lastName: data.LastName,
email: data.Email,
photoUrl: downloadURL,
});
});
}
);
}
I wrote the setDoc
function in there because I need the downloadUrl
so I can add it to the doc. However I don't get any error and the document never gets created does anyone know why?
Your handling of UploadTask.on() has skipped the nextObserver which results in incorrect callback usage. The parameters are, in order...
on(event, nextObserver, error, complete)
You can treat the upload task like a promise since you only seem interested in its completion or failure which would simplify your code quite a lot
try {
const uploadSnapshot = await uploadBytesResumable(storageRef, profileIcon);
const downloadUrl = await getDownloadUrl(uploadSnapshot.ref);
await updateProfile(user.user, {
displayName: `${data.FirstName} ${data.LastName}`,
photoURL: downloadURL,
});
await setDoc(doc(db, "users", user.user.uid), {
uid: user.user.uid,
displayName: `${data.FirstName} ${data.LastName}`,
firstName: data.FirstName,
lastName: data.LastName,
email: data.Email,
photoUrl: downloadURL,
});
} catch (err) {
setError(true);
console.error(error);
}