Hendry Lim
Hendry Lim

Reputation: 1974

Accessing Parent Key from Child using Firebase

I am using firebase. I have 2 collections - User Docs and Docs. I am iterating through the User Docs to get the Docs which will then return an array of docs under a User. As the parent key (as shown in code below) lies in the first loop, how can I access it in my child loop? ( I need the parent key because it contains the unique values which I require for my FlatList component). Thanks a lot for your guidance in advance :)

_fetchMyDocs = () => {
const { currentUser } = firebase.auth();

const rootRef = firebase.database().ref();
const userDocsRef = rootRef.child(`userDocs/${currentUser.uid}`);

const arr = [];
userDocsRef.on("child_added", snap => {

  console.log("PARENT KEY: ", snap.key);

  const { docId } = snap.val();
  const docsRef = rootRef.child(`coDocs/${docId}`);

  docsRef.on("value", snap => {

  console.log("CHILD KEY: ", snap.key, "CHILD VAL: ", snap.val());

    const key = snap.key;
    const { docUrl, companyId, companyName } = snap.val();
    arr.push({
      key,
      companyId,
      companyName,
      docUrl
    });
        return arr
   });
 });
};

Upvotes: 0

Views: 357

Answers (1)

Ravi
Ravi

Reputation: 35549

There are 2 ways you can use it

1) Store it in variable

var parentKey = snap.key

2) Use some other name for response in docsRef

docsRef.on("value", child => {

and then use directly using snap.key

Upvotes: 1

Related Questions