Build A Simple Dapp in 3 Mins - Real Time Transactions (Part 4)

Build your first Moralis Dapp! This guide series covers the basics and how to get started fast. In part 4, we subscribe to our query to get real-time alerts.

How to get real time data

Not only can we get all past transactions, but we get get notifications when new transactions happen!

Just subscribe to the query

const subscription = await query.subscribe();

And handle the events

subscription.on("create", function(data) {
console.log("new transaction: ", data);
});

That's it!... we can modify our getUserTransactions() function as follows.

async function getUserTransactions(user) {
// create query
const query = new Moralis.Query("EthTransactions");
query.equalTo("from_address", user.get("ethAddress"));
// subscribe to query updates ** add this**
const subscription = await query.subscribe();
handleNewTransaction(subscription);
// run query
const results = await query.find();
console.log("user transactions:", results);
}
async function handleNewTransaction(subscription) {
// log each new transaction
subscription.on("create", function(data) {
console.log("new transaction: ", data);
});
}

Now whenever the user makes a new transaction on Mainet it will print a message.

Outstanding!

Real time action! Can't stop now we're almost to the finish line... keep going!