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>
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);
});
}
Related Questions
- → How to update data attribute on Ajax complete
- → October CMS - Radio Button Ajax Click Twice in a Row Causes Content to disappear
- → Octobercms Component Unique id (Twig & Javascript)
- → Passing a JS var from AJAX response to Twig
- → Laravel {!! Form::open() !!} doesn't work within AngularJS
- → DropzoneJS & Laravel - Output form validation errors
- → Import statement and Babel
- → Uncaught TypeError: Cannot read property '__SECRET_DOM_DO_NOT_USE_OR_YOU_WILL_BE_FIRED' of undefined
- → React-router: Passing props to children
- → ListView.DataSource looping data for React Native
- → Can't test submit handler in React component
- → React + Flux - How to avoid global variable
- → Webpack, React & Babel, not rendering DOM