I am working on a reactjs web application which interacts with a solidity smartcontract.
This smartcontract emit events and i want to listen to this events in my web application.
Here is my react js file:
import React, { useState, useEffect } from "react";
import getWeb3 from "./getWeb3";
import Contract1 from "./contracts/Contract1.json";
const App = () => {
// Hooked variables
const [web3, setWeb3] = useState(null);
const [account, setAccount] = useState(null);
const [contract, setContract] = useState(null);
function callback(event) {
console.log(account); // Problem: Every hooked variables are null here
}
async function init() {
const web3 = await getWeb3();
const accounts = await web3.eth.getAccounts();
const networkId = await web3.eth.net.getId();
setAccount(accounts[0]);
let deployedNetwork = Contract1.networks[networkId];
let _contract = new web3.eth.Contract(Contract1.abi, deployedNetwork && deployedNetwork.address);
_contract.events.MyEvent().on("data",(e) => callback(e));
setContract(_contract);
setWeb3(web3);
...
};
useEffect(() => { init(); }, []);
...
Everything works fine in my application.
callback function is called When MyEvent is emit from my smartcontract.
But there is something very strange: Every hooked variables are null in callback function.
I suppose this is a scope issue because this variables are set and works fine elsewhere in my application.
You can use another useEffect to watch account and contract, then you can subscribe and unsubscribe when account change
useEffect(() => {
if(account && _contract){
_contract.events.MyEvent().on("data",(e) => {
});
}
return () => {
//unscubscribe here
}
}, [account, _contract])