This is my markup/HTML where the table will be inserted:
<section class="page page-info">
<div class="contact">
<div class="container">
<div class="row">
<div class="col-sm-8 col-sm-offset-2">
<table>
<!-- Table goes here! -->
</table>
</div>
</div>
</div>
</div>
</section>
Some variables in the outer scope so they can be accessed by all functions, followed by the fetch call and the table creating module :
var products;
let table = document.querySelector('table');
window
.fetch('/pages/products-api')
.then(resp => resp.json())
.then(function(data) {
products = data;
GenerateTableModule.initialize(table, products);
console.log('data.results ', data);
})
.catch(err => console.dir(err));
const GenerateTableModule = (function() {
let table = null;
let data = [];
function initialize(tableSelector, arr) {
table = tableSelector;
data = arr;
}
const _generateTableHead = function() {
let thead = table.createTHead();
let row = thead.insertRow();
for (let key in data[0]) {
let th = document.createElement('th');
let text = document.createTextNode(key);
th.appendChild(text);
row.appendChild(th);
}
};
const generateTable = function() {
for (let element of data) {
let row = table.insertRow();
for (key in element) {
let cell = row.insertCell();
let text = document.createTextNode(element[key]);
cell.appendChild(text);
}
}
_generateTableHead();
};
return { initialize, generateTable };
})();
GenerateTableModule.generateTable();
The actual error I get in the console is:
updating-upsell-on-the-view-cart.js?25617:26 Uncaught TypeError: Cannot read property 'createTHead' of null at _generateTableHead (updating-upsell-on-the-view-cart.js?25617:26) at Object.generateTable (updating-upsell-on-the-view-cart.js?25617:45) at updating-upsell-on-the-view-cart.js?25617:50
But how can that be when I have my data being returned in the console.log
in my fetch?!
data.results {products: Array(88)}
Thanks in advance!