Search code examples
javascriptreactjsarraysundefined

Cannot access array data in reactjs


When I'm trying to get data of getObjectives function, I have got undefined. I don't know where is the problem, in the function or in the code

The function GetObjectives()

export async function GetObjectives(docId) {
  try {
    const querySnapshot = await getDocs(collection(db, "users", "userIdNotAvailableForTheMoment", "documents", docId, "nodes"));
    const objectivesArray = [];

    querySnapshot.forEach(async (nodeDoc) => {
      const nodeId = nodeDoc.id;
      const objectivesQuerySnapshot = await getDocs(collection(db, "users", "userIdNotAvailableForTheMoment", "documents", docId, "nodes", nodeId, "objectives"));

      const objectivesData = objectivesQuerySnapshot.docs.map((objectiveDoc) => ({
        ...objectiveDoc.data(),
        id: objectiveDoc.id
      }));
      objectivesArray.push(objectivesData);
    });

    return objectivesArray;
  } catch (error) {
    console.error('Error during the recuperation of objectives : ', error);
    return null;
  }
}

An example of the code when I get data

GetObjectives(sortDocuments[parseInt(selectedDocument)].id, result[0].id)
  .then(async (result) => {
    console.log(result)
    console.log(result[0])
});

Reponses : console.log(result) return what I want, however console.log(result[0]) return undefined but I didn't know why

//console.log(result)
[
    [        
        {
            "parents": [],
            "childrens": [],
            "content": "value",
            "id": "VULpo5mPCc2kckLC9BCy",
            "title": "value"
        }
    ],
    [
        {
            "parents": [],
            "childrens": [],
            "content": "value",
            "id": "VULpo5mPCc2kckLC9BCy",
            "title": "value"
        }
    ]
]

//console.log(result[0])
Undefined

Solution

  • While I can't explain the console output, I strongly believe that part of the issue is that GetObjectives() is actually returning an array of promises rather than array of resolved objects. You can use Promise.all() to resolve the array of promises "in parallel". Does the following implementation of GetObjectives() fix your issue?

    export async function GetObjectives(docId) {
      try {
        const querySnapshot = await getDocs(collection(db, "users", "userIdNotAvailableForTheMoment", "documents", docId, "nodes"));
    
        const objectivesArray = querySnapshot.map(async (nodeDoc) => {
          const nodeId = nodeDoc.id;
          const objectivesQuerySnapshot = await getDocs(collection(db, "users", "userIdNotAvailableForTheMoment", "documents", docId, "nodes", nodeId, "objectives"));
    
          return objectivesQuerySnapshot.docs.map((objectiveDoc) => ({
            ...objectiveDoc.data(),
            id: objectiveDoc.id
          }));
        });
    
        return Promise.all(objectivesArray);
      } catch (error) {
        console.error('Error during the recuperation of objectives : ', error);
        return null;
      }
    }