Build A Simple Dapp in 3 Mins - Historical Transactions (Part3)

How to get historic data

Getting the past transactions for the logged in user is as simple as creating a query on the EthTransactions table.

const user = Moralis.User.current();
const query = new Moralis.Query("EthTransactions");
query.equalTo("from_address", user.get("ethAddress"));
const results = await query.find();

Add a new button

Add a new button to the html body under the other ones. Can use this to manually get the stats.

<button id="btn-get-stats">Refresh Stats</button>

Create a query and call it

Add the following code to the <script> tag under the previous code.

document.getElementById("btn-get-stats").onclick = getStats;
function getStats() {
const user = Moralis.User.current();
if (user) {
getUserTransactions(user);
}
}
async function getUserTransactions(user) {
// create query
const query = new Moralis.Query("EthTransactions");
query.equalTo("from_address", user.get("ethAddress"));
// run query
const results = await query.find();
console.log("user transactions:", results);
}
// get stats on page load
getStats();

And call getStats() from the login() function like so

async function login() {
let user = Moralis.User.current();
if (!user) {
user = await Moralis.Web3.authenticate();
}
console.log("logged in user:", user);
// ** add this **
getStats();
}

Check the results

Save the changes. The dapp page should be updated automatically. You'll see something like this in the console.

Code so far

<html>
<head>
<!-- Moralis SDK code -->
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/web3.min.js"></script>
<script src="https://unpkg.com/moralis/dist/moralis.js"></script>
</head>
<body>
<h1>Moralis Gas Stats</h1>
<button id="btn-login">Moralis Login</button>
<button id="btn-logout">Logout</button>
<button id="btn-get-stats">Refresh Stats</button>
<script>
// connect to Moralis server
Moralis.initialize("TCDv7lnGwNN7RIhlj30wA69dnaamxtsmqcTnm3ch");
Moralis.serverURL = "https://9c8nrl6lfq8u.moralis.io:2053/server";
async function login() {
let user = Moralis.User.current();
if (!user) {
user = await Moralis.Web3.authenticate();
}
console.log("logged in user:", user);
getStats();
}
async function logOut() {
await Moralis.User.logOut();
console.log("logged out");
}
// bind button click handlers
document.getElementById("btn-login").onclick = login;
document.getElementById("btn-logout").onclick = logOut;
document.getElementById("btn-get-stats").onclick = getStats;
function getStats() {
const user = Moralis.User.current();
if (user) {
getUserTransactions(user);
}
}
async function getUserTransactions(user) {
// create query
const query = new Moralis.Query("EthTransactions");
query.equalTo("from_address", user.get("ethAddress"));
// run query
const results = await query.find();
console.log("user transactions:", results);
}
//get stats on page load
getStats();
</script>
</body>
</html>

OMG!

Historic working! Yeaaaa... keep going!