-1

When I am trying to print defaultAccount State as shown below code, it still showing null even after setting it to the metamask account as shown in picture below, it is throwing me a null value, when printing defaultAccount. (Please refer error in the below Image)

 class App extends Component {
constructor(){
super()
this.state={
  defaultAccount:null,
  provider:null,
  connectState:false,
  ethers:null,
  gameContract:null
}

this.loadWindow=this.loadWindow.bind(this)
}



async loadWindow(){
if (window.ethereum){
  try{
    const accounts =await window.ethereum.request({method: 'eth_requestAccounts',});
    console.log(accounts[0])
    const contractAbi=[
      "function getRandomNumber() public returns(bytes32 requestId)",
      "function fulfillRandomness(bytes32 requestId,uint randomness) internal override",
      "function contractBalance() public view returns(uint)"
    ]
    const provider=  new ethers.providers.Web3Provider(window.ethereum,"any")
    const signer = await provider.getSigner()
    const gameContract=new ethers.Contract("0x6cEB2a506b6b1145241BC92D4CFD94aE5588eB18",contractAbi,signer)

    this.setState({defaultAccount:accounts[0],connectState:true,provider:provider,ethers:ethers,gameContract:gameContract});
    
    
    console.log(this.state.defaultAccount)
  }catch(e){
console.log(e)
  }
  
  window.alert("Wallet Connected..")
}
else{
  window.alert("Metamask Not Found..")
}

}

Error Message

Azzor
  • 11
  • 2

1 Answers1

0

The reason the console.log is printing null, is because the setState updates in React happen asynchronously. This is to increase the performance of React. This is explained more in detail here.

If you want to log the state directly after it has been updated, you can add a callback function to the setState call like this:

    this.setState({defaultAccount:accounts[0],connectState:true,provider:provider,ethers:ethers,gameContract:gameContract}, () => console.log(this.state.defaultAccount));
Jesper Paulsen
  • 311
  • 3
  • 8