0

I am trying to make a request to get all the events of a user, then get the detail of this events in a list. I don't find a right solution to do that.

Database

enter image description here

Actions index

enter image description here

So at the moment, I only get the user's travel, but not the detail of each event that the user have.

Thank you for your help

KENdi
  • 7,576
  • 2
  • 16
  • 31
  • A quick answer below. In future questions please post code and JSON as text, and not as screenshots. You can get the JSON as text by clicking the "Export JSON" link in your [Firebase Database console](https://console.firebase.google.com/project/_/database/data). – Frank van Puffelen Oct 30 '18 at 14:38

1 Answers1

0

You'll need to do another on() or once() for each event inside your current callback, and load the additional data. This process is known as a client-side join. Then within the inner loop you can dispatch the results, either on each load or when all are loaded.

Code (untested, so there may be typos):

usersRef.child(uid).child("events").on("value", snapshot => {
  var promises = []
  snapshot.forEach(eventSnapshot => {
    promises.push(eventsRef.child(eventSnapshot.key).once("value"));
  })
  Promise.all(promises).then(eventSnapshots => {
    // eventSnapshots contains the details of all events
    return eventSnapshot.map(eventSnapshot => eventSnapshot.val());
  }).then(events => {
    dispatch({ type: FETCH_EVENTS, payload: events });
  });
})

Alternatively you can duplicate the minimal data for each event under /users/$uid/events/$eventid`. This duplicates data, but prevents the need for client-side joins. This type of read-vs-write trade-off is very common when using NoSQL databases. For strategies for the duplicated data up to date, see How to write denormalized data in Firebase.

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807