Listen to new blocks
This example shows how to subscribe to new blocks.
It displays the block number every time a new block is seen by the node you are connected to.
NOTE: The example runs until you stop it with CTRL+C
const Rpc = require('@polkadot/rpc-core').default;
const WsProvider = require('@polkadot/rpc-provider/ws').default;
const provider = new WsProvider('ws://127.0.0.1:9944');
const api = new Rpc(provider);
api.chain
.newHead((error, header) => {
if (error) {
console.error('error:', error);
}
console.log(`best #${header.blockNumber.toString()}`);
})
.then((subscriptionId) => {
console.log(`subscriptionId: ${subscriptionId}`);
// id for the subscription, can unsubscribe via
// api.chain.newHead.unsubscribe(subscriptionId);
})
.catch((error) => {
console.error('error subscribing:', error);
});