DEV Community

Rossano D'Angelo
Rossano D'Angelo

Posted on

How to fetch subcollections from Cloud Firestore with React

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) => {
    .then(response => {
      response.forEach(document => {
        // access the movie information
    .catch(error => {
{ => (
  <li key={} onClick={() => selectCinema(cinema)}>
    <b>{}</b> in {} has {cinema.total_seats} total seats
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

Top comments (2)

gkranasinghe profile image

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

lucianoschillagi profile image

and what is your solution for this case?