0

I'm trying to get all documents from a firebase collection, create a list and return it on request with a Cloud Function, but I'm struggling with the asynchronous nature of JavaScript. Here's my code so far:

firebase.initializeApp(firebaseConfig);
const db = firebase.firestore();

const items = "";

async function buildItems() {
    db.collection("reminders").get().then((QuerySnapshot) => {
        QuerySnapshot.forEach((item) => {
            items.concat("<li>" + item.data().name + "</li>");
            console.log(items);
        });
    })
}
exports.view = functions.https.onRequest((req, res) => {
    buildItems().then(
        res.status(200).send(`<!doctype html>
    <head>
      <title>Reminders</title>
    </head>
    <body>
      <ul>
        ${items}
      </ul>
    </body>
  </html>`))});

EDIT: Include Promises-based code I've tried (it's wrong, I don't know how to solve it)

firebase.initializeApp(firebaseConfig);
const db = firebase.firestore();

function buildItems() {
    return new Promise((resolve) => {
        resolve(db.collection("reminders").get())
    });
}
exports.view = functions.https.onRequest((req, res) => {
    buildItems(reminders => {
        let items = "";
        reminders.then((qs) => {
            qs.forEach(items.concat("<li>" + qs.data().name + "</li>"))
        }).then(resolve(items));
    }).then( items =>
        res.status(200).send(`
  <!doctype html>
    <head>
      <title>Reminders</title>
    </head>
    <body>
      <ul>
        ${items}
      </ul>
    </body>
  </html>`))});

The output is always the same: absolutely nothing is displayed on the browser or to the console. I've tried variations of this code, but no success so far.

Thanks in advance!

MucaP
  • 992
  • 1
  • 10
  • 18
  • Your function is trying to use `items` before it gets set. You can verify this by adding more console logs. I think you'll need to look into a more correct use of promises. You don't need a global variable here - buildItems should just be returning a promise that resolves to the data you want the calling function to use. – Doug Stevenson Sep 29 '19 at 20:03
  • @DougStevenson I've tried that, the code is now on the question. – MucaP Sep 29 '19 at 23:44

1 Answers1

1

I cleaned the code up a bit and replaced your Promise based code with async await. You can try running this:

async await version

firebase.initializeApp(firebaseConfig);
const db = firebase.firestore();

const buildItems = async () => {
  return db.collection('reminders').get();
};

exports.view = functions.https.onRequest(async (req, res) => {
  try {
    const reminders = await buildItems();
    let items = '';

    reminders.forEach(qs => {
      items.concat(`<li> ${qs.data().name} </li>`);
    });

    return res
      .status(200)
      .send(`
        <!doctype html>
        <head>
            <title>Reminders</title>
            </head>
            <body>
            <ul>
                ${items}
            </ul>
            </body>
        </html>
        `);
  } catch (error) {
    /** Handle error here */
  }
});

Promise based version

firebase.initializeApp(firebaseConfig);
const db = firebase.firestore();

const buildItems = () => {
  return db.collection('reminders').get();
};

exports.view = functions.https.onRequest((req, res) => {
  buildItems()
    .then(reminders => {
      let items = '';
      reminders.forEach(qs => {
        items.concat(`<li> ${qs.data().name} </li>`);
      });

      return res
        .status(200)
        .send(`
        <!doctype html>
        <head>
            <title>Reminders</title>
            </head>
            <body>
            <ul>
                ${items}
            </ul>
            </body>
        </html>
        `);
    })
    .catch(error => {
      /** Handle Error here */
    });
});

If you are having still having trouble, you should try if the collection reminders actually contains the documents you want to fetch.

The .size property is available in [QuerySnapShots][1] in Firebase query snapshot results. If the snapshot size is 0.

Utkarsh Bhatt
  • 1,536
  • 2
  • 14
  • 23
  • I've tried both approaches, but none of them seem to work. No errors are displayed, just shows nothing to the browser. – MucaP Oct 01 '19 at 19:17
  • @MucaP. Can you try console logging the value of `qs.data()`. What's the size of your collection? – Utkarsh Bhatt Oct 02 '19 at 08:43
  • 3 items. The collection isn't the problem, i can assure you that since I'm using similar code to solve other problems. – MucaP Oct 02 '19 at 19:07