Ad

How To Assign A Variable As Fieldname Holder When Using Doc.data(). In Firebase To Retrieve Data

I am trying to recieve data from firebase cloud firestore. I have a collection called 'profiles', a doc called user and I have fields like favorite_music, favorite_book, favorite_movie. I want to recieve data based on an Input recieved from an html page.

I want to pass variable get on data.doc.get . How should I rewrite this code to make it work?

JS code

db.collection("profiles").doc("user").get().
then(snapshot => {
    snapshot.doc.forEach(
        doc => {
            displayfunction(doc)
        });
)
});

document.getElementById("hit")
    .addEventListener("submit", function() {
        var get = document.getElementById("fav").value;

        function displayfunction(doc) {
            let requested_item = document.createElement('p');
            requested_item.textContent = doc.data().get;
            var displayele = document.getElementById("display");
            displayele.appendChild(requested_item);
        }

    })

html code

<select id="fav">
<option value="favorite_music">my music</option>
<option value="favorite_book">my book</option>
</select>
<div id="display">
</div>
<button type="submit" id="hit"> submit </button>
Ad

Answer

This should do it. The problem with your code is that you were running the query at the top, independent of the submit event. Your displayFunction was also scoped to the submit handler, so it couldn't be invoked outside of that scope.

What you really want is to define a function that gets the documents--getUserProfiles--and call it on the submit event. You pass getUserProfiles a callback that does the work.

document.getElementById('hit').addEventListener('submit', function() {
  getUserProfiles(function displayFunction(doc) {
    const displayEl = document.getElementById('display');
    const requestedItem = document.createElement('p');
    const data = doc.data();

    requestedItem.textContent = data.whateverMyAttributeNameIs;

    displayEl.appendChild(requestedItem);
  });
});

function getUserProfiles(callback) {
  return db
    .collection('profiles')
    .doc('user')
    .get()
    .then(snapshot => {
      snapshot.doc.forEach(callback);
    });
}

Ad
source: stackoverflow.com
Ad