loading...

How to fetch subcollections from Cloud Firestore with React

rossanodan profile image Rossano D'Angelo ・1 min read

More data!

First, I add more data to my database. Just to make things more realistic. For each cinema I add a subcollection movies in which I add some movies. Each movie has this info

name: string,
runtime: string,
genre: string,
release_date: timestamp
Enter fullscreen mode Exit fullscreen mode

In Firestore, data can also have different structure (NoSQL's power!) but, for simplicity, I follow the canonical way.

Alt Text

I add one movie for the first cinema and two movies for the second one.

Fetching the subcollection

I make the cinemas list clickable, so when I click an item I load movies scheduled for that specific cinema. To do this, I create a function selectCinema that will perform a new query to fetch a specific subcollection.

...
const selectCinema = (cinema) => {
  database.collection('cinemas').doc(cinema.id).collection('movies').get()
    .then(response => {
      response.forEach(document => {
        // access the movie information
      });
    })
    .catch(error => {
      setError(error);
    });
}
..
{cinemas.map(cinema => (
  <li key={cinema.id} onClick={() => selectCinema(cinema)}>
    <b>{cinema.name}</b> in {cinema.city} has {cinema.total_seats} total seats
  </li>
))}
Enter fullscreen mode Exit fullscreen mode

At this point is easy managing the show/hide logic with React using the state.

A working demo

Gaunt but working.

Alt Text

Discussion

pic
Editor guide
Collapse
gkranasinghe profile image
gkranasinghe

Associating a hook with query will cause infinite rerendering of the component ,as useState will rerender the component ,which will lead to reexecute the Query .I think this is really a bad practice