Home > Mobile >  How can I print the Firebase array elements that I see in the console, to display them on the webpag
How can I print the Firebase array elements that I see in the console, to display them on the webpag

Time:06-23

This is my first time using Firebase. So I'm kind of stuck at at point where I can see the data I've fetched from the database in the console but I don't have a clue how to access the data elements and maybe display them.

I used a react hook to retrieve the data.

  React.useEffect(() => {
    const dbRef=ref(db,"thisIsMyDatabaseString");
    onValue(dbRef,(snapshot)=>{
      console.log(snapshot.val());
    })
  },[]);

I can see the array elements

like this

I don't know how to maybe display them in a Grid (I'm using material UI).

Any help would be appreciated. Thanks!

CodePudding user response:

You can use Firebase's built-in forEach on the snapshot:

const dbRef=ref(db,"thisIsMyDatabaseString");
onValue(dbRef,(snapshot)=>{
  snapshot.forEach((child) => {
    console.log(child.val());
  })
})

Note that such sequential numeric indexes are a common anti-pattern in Firebase, so I recommend also reading Best Practices: Arrays in Firebase.

  • Related