How fetch data from firebase realtime database in react js

Viewed 739

I am trying to fetch data from Firebase in React. My data is structured like this:

enter image description here

My code currently looks like this:

fire.database().ref(outputClassName).once("value", snapshot => {
      let classStudents = [];
      snapshot.forEach(snapsh => {
        //classStudents.push(snapsh.val());
        let student = "";
        student = snapsh.val();
        alert(student);
        fire.database().ref(outputClassName).child(student).once("value", snapsho => {
          let studentSubjects = [];
          snapsho.forEach(snaps => {
            //studentSubjects.push(snaps.val());

            fire.database().ref(outputClassName).child(student).child(snaps.val()).once("value", snapsh => {
              let subjectNotes = [];
              snapsh.forEach(snap => {

                subjectNotes.push(snap.val());

              });

              studentSubjects.push(subjectNotes);

            });
          });

          classStudents.push(studentSubjects);

        });

      });
      setRenderData(classStudents);
    });

I am getting an error for this code. Can someone help me with a working solution ?

1 Answers

You should use .once() instead of .on() when data has to fetched only once. Also when you fetch data at path /10 A, it will fetch the complete node so you don't have to request data of every student in that class again.

function outputData() {
    fire.database().ref(outputClassName).once("value").then((snapshot) => {
      const classData = snapshot.val()
      const students = Object.keys(classData)

      students.forEach((student, i) => {
        const subjects = Object.keys(classData[student])
        console.log(`${i+1} Name: ${student}`)
        console.log(`Subjects: ${JSON.stringify(subjects)}`)
        console.log("===")

        // render the data to HTML as per needs
      })
    })
}
Related