I am trying to created 2 docs at ones what first docs id is used in the second. One problems is my code look wired, especially the chaining. I am afraid even if it works that it might be wrong.
Any idea for a more clear refactor? The flow is the following:
const Signup = async (email: string, password: string) => {
await createUserWithEmailAndPassword(auth, email, password)
.then((userCredential) => {
const user = userCredential.user;
const colRef = collection(db, 'Shared');
addDoc(colRef, {
sharedValue: '',
}).then((res) =>
setDoc(doc(db, 'Data', user.uid), {
sharedId: res.id,
})
);
})
.catch((error) => {
console.log(error)
});
};
As shown in the documentation on adding a document:
In some cases, it can be useful to create a document reference with an auto-generated ID, then use the reference later. For this use case, you can call
doc().import { collection, doc, setDoc } from "firebase/firestore"; // Add a new document with a generated id const newCityRef = doc(collection(db, "cities")); // later... await setDoc(newCityRef, data);
So:
await createUserWithEmailAndPassword(auth, email, password)
.then((userCredential) => {
const user = userCredential.user;
const colRef = collection(db, 'Shared');
const docRef = doc(db, 'Shared');
setDoc(docRef, {
sharedValue: '',
}).then((res) =>
setDoc(doc(db, 'Data', user.uid), {
sharedId: docRef.id,
})
);
})
.catch((error) => {
console.log(error)
});
};