0

When i want to display data from firestore in node.js, i get an error on this code: productsContainer.appendChild(article);

With this error: Firestore Uncaught (in promise) TypeError: Cannot read property 'appendChild' of null

const myProducts = db.collection('products').doc('fruit');
const productsContainer = document.querySelector('#groceries');

 function renderProduct(data) {
   const docFrag = document.createDocumentFragment();
   let article = document.createElement('article');
   let productName = document.createElement('h4');
   let productPrice = document.createElement('p');

   article.setAttribute('id', data.id);
   productName.textContent = data.name;
   productPrice.textContent = data.price;

   docFrag.appendChild(productName);
   docFrag.appendChild(productPrice);

   article.appendChild(docFrag);
   productsContainer.appendChild(article);
 }

myProducts.get().then(function(documentSnapshot) {
  if (documentSnapshot.exists) {
    var products = documentSnapshot.data();
    console.log(products);
    renderProduct(products);
  }
});

class contact extends React.Component {

  render() {
      return (
          <div className="app-wrapper">
              <ContainerHeader match={this.props.match} title={<IntlMessages id="appModule.contactSupport"/>}/>
              <div className="d-flex justify-content-center">
                    <div id="groceries"></div>
              </div>
          </div>
      );
  }
}

console firestore

Community
  • 1
  • 1
Orbi
  • 61
  • 7
  • 1
    That means `productsContainer` (and `document.querySelector("#groceries")`) is `null`. See [Why does jQuery or a DOM method such as getElementById not find the element?](https://stackoverflow.com/q/14028959/4642212). In this case, your element isn’t in the DOM yet—your React component isn’t rendered at the time `const productsContainer` is defined. – Sebastian Simon Nov 11 '19 at 17:22
  • Thanks for the good help. I used **window.onload = function()** to accomplish. It works perfect. – Orbi Nov 12 '19 at 11:45
  • That’s not a good approach. Use `addEventListener("DOMContentLoaded", function(){` … `});` instead. – Sebastian Simon Nov 12 '19 at 11:48

0 Answers0