Firebase: How To Submit Form Data To Different Collections?
I have one form. One of the fields in the form is a Field Array - for repeatable fields. Apart from this field, all the other form fields are stored in a single collection (the Par
Solution 1:
Every time you call doc()
, you're going to generate a reference to a new randomly generated document. That means your first call to firestore.collection("glossary").doc()
will generate a new ID, as well as the subsequent call. If you want to reuse a document reference, you're going to have to store it in a variable.
const firstDocRef = firestore.collection("glossary").doc()
firstDocRef.set(...)
The use that same variable later:
const secondDocRef = firstDocRef.collection('relatedTerms').doc()
secondDocRef.set(...)
Solution 2:
I don't have enough karma or whatever to comment so I'm putting my comment here.
Here's one way to implement Doug's solution with your code. Sorry in advanced for any syntax errors -- I did not test run this code.
You can pass document ids before execution even though the autoID is generated when the submit is made.
onSubmit={(values, { setSubmitting }) => {
setSubmitting(true);
const newDocRef = firestore.collection("glossary").doc() // auto generated doc id saved herelet writeBatch = firestore.batch();
writeBatch.set(newDocRef,{
term: values.term,
definition: values.definition,
category: values.category,
context: values.context,
createdAt: firebase.firestore.FieldValue.serverTimestamp()
}),
writeBatch.set(newDocRef.collection('relatedTerms').doc(),{
dataType: values.dataType,
title: values.title,
description: values.description,
})
writeBatch.commit()
.then(() => {
setSubmitionCompleted(true);
});
}}
Post a Comment for "Firebase: How To Submit Form Data To Different Collections?"