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 Four, 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 can also get notifications when new transactions happen!

Just Subscribe to the Query

1
const subscription = await query.subscribe();
Copied!

And Handle the Events

1
subscription.on("create", function(data) {
2
console.log("new transaction: ", data);
3
});
Copied!
That's it!... we can modify our getUserTransactions() function as follows:
1
async function getUserTransactions(user) {
2
// create query
3
const query = new Moralis.Query("EthTransactions");
4
query.equalTo("from_address", user.get("ethAddress"));
5
​
6
// subscribe to query updates ** add this**
7
const subscription = await query.subscribe();
8
handleNewTransaction(subscription);
9
​
10
// run query
11
const results = await query.find();
12
console.log("user transactions:", results);
13
}
14
​
15
async function handleNewTransaction(subscription) {
16
// log each new transaction
17
subscription.on("create", function(data) {
18
console.log("new transaction: ", data);
19
});
20
}
Copied!
Now, whenever the user makes a new transaction on the mainnet, it will print a message.

Outstanding!

Real-time action! Can't stop now, we're almost to the finish line... keep going!
​
Last modified 1mo ago