You have to take care of following things:
Use websocket provider in order to subscribe to events in web3.js 1.0. For example, if you are using local TestRPC then instantiate the web3 as by using your websocket port (here in this case its 8545):
const web3 = new Web3(Web3.givenProvider || "ws://127.0.0.1:8545");
The example code for myContract
having an event of MyEvent
will be like:
myContract.events.MyEvent ({
fromBlock: 'latest',
toBlock: 'latest'
}, function(error, result) {
if (!error) {
console.log(result);
} else {
console.log(error);
}
});
Note: in the above block of code, I'm watching for the events in 'latest'
block mined. The reason is, this block of code is the same as we have watch
method in the older version. This will only watch for events that are not fired yet. If you want to get
all the events, you have to use getPastEvents
:
myContract.getPastEvents('MyEvent', {
fromBlock: 0,
toBlock: 'latest'
}, function(error, result) {
if (!error) {
console.log(result);
} else {
console.log(error);
}
});
For more details, see the Docs