简体   繁体   中英

How can I listen the event emitted from smart contract in web3 js?

I am now building NFT staking website and I have an issue.

I have built smart contract and made it to emit the event. But in frontend, I cannot listen the event emitted properly. So I force listen to the event with hard coding. The code is following.

var stakeTokenEvent = stakeToken.events.Staked();

let event = await stakeTokenEvent.on({}, function (error, result) {
  if (!error) {
    return result;
  } else {
    dispatch(spinner_show());
  }
});
new Promise(function (resolve, reject) {
  if (event) {
    resolve("success");
  } else {
    reject("error");
  }
}).then(
  (success) => {
    dispatch(ghsp_connect());
  },
  (error) => {}
);

Are there any easy method or proper way to listen to the event emitted?

from web3 doc( myContract.events.NameOfYourEvent() )

It's simple example:

    myContract.events.MyEvent([filter options])
      .on("connected", function(subscriptionId){ console.log(subscriptionId);})
      .on('data', function(event){ console.log(event);})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM