I have here this code that gets me the latest pair from a smart contract:
document.getElementById("latestPairs").innerHTML = `<table class="table table-dark table-striped table-hover" id="latest"></table>`;
const table = document.getElementById("latest");
const rowHeader = `<thead>
<tr>
<th>Token0</th>
<th>Token1</th>
<th>Pair</th>
</tr>
</thead>`
table.innerHTML = rowHeader;
pcsfactoryC.events.PairCreated({fromBlock:'latest'})
.on('data', async function(event){
//console.log(event.returnValues);
// Do something here
let pairs = event.returnValues
let token0 = event.returnValues['token0'];
let token1 = event.returnValues['token1'];
let getPair = event.returnValues['pair'];
console.log(token0 " " token1);
add_row("latest", [event.returnValues['token0'], event.returnValues['token1'], event.returnValues['pair']]);
})
.on('error', console.error);
It works in the console as expected however the rows arent beeing added to the table and i receive following error:
Uncaught (in promise) ReferenceError: add_row is not defined
How can i fix this and make a dynamic table for my data?
CodePudding user response:
You have to create your own add_row function since it is not a built in function within js
Also the async function seems unnecessary since you are not using await.
CodePudding user response:
You can simply append innerHTML to table. Wrap each row with <tr>
and each column with <td>
.
function add_row(id, token0, token1, pair){
var table = document.getElementById(id);
const rowdata = "<tr><td>" token0 "</td><td>" token1 "</td><td>" pair "</td></tr>";
table.innerHTML = rowdata;
}
add_row v2 (Insert to top instead of bottom)
function add_row(id, token0, token1, pair){
var table = document.getElementById(id);
var thead = document.querySelector('#' id ' thead').innerHTML;
const firstrowdata = "<tbody><tr><td>" token0 "</td><td>" token1 "</td><td>" pair "</td></tr></tbody>";
const rowdata = "<tr><td>" token0 "</td><td>" token1 "</td><td>" pair "</td></tr>";
if(table.rows.length == 1)table.innerHTML = firstrowdata;
else{
var tbody = document.querySelector('#' id ' tbody').innerHTML;
table.innerHTML = "<thead>" thead "</thead>" "<tbody>" rowdata tbody "</tbody>";
}
}
If you want to test it out, you need to change the way you call add_row()
:
/* Removed outer [ ] after ("latest", */
add_row("latest", event.returnValues['token0'], event.returnValues['token1'], event.returnValues['pair']);