0

I am getting the above error and the code is mentioned below. Is this error related to the code or version of web3?. Unable to get transaction receipt.

 try{
        this.setState({blockNumber:"waiting.."});
        this.setState({gasUsed:"waiting..."});

        // get Transaction Receipt in console on click
        // See: https://web3js.readthedocs.io/en/1.0/web3-eth.html#gettransactionreceipt
        await web3.eth.getTransactionReceipt(this.state.transactionHash, (err, txReceipt)=>{
          console.log(err,txReceipt);
          this.setState({txReceipt});
        }); //await for getTransactionReceipt

        await this.setState({blockNumber: this.state.txReceipt.blockNumber});
        await this.setState({gasUsed: this.state.txReceipt.gasUsed});    
      } //try
    catch(error){
        console.log(error);
      } //catch
  } //onClick
  
TylerH
  • 20,799
  • 66
  • 75
  • 101
happy2
  • 11
  • 2
  • 3
    this.state.txReceipt is null so you can't read blockNumber property from it – Joe Taras Jul 08 '20 at 09:30
  • 1
    Aside from the above... Assuming the `setState` here is from React, then: 1. State updates may be asynchronous, so you can't rely on something being in `this.state` after a `setState` call. 2. Although state updates may be asynchronous, `setState` doesn't return a promise, there's no point in `await`ing it. Use the completion callback (or promisify it). 3.When you have multiple state items to update directly, a single call is probably better than multiple calls. – T.J. Crowder Jul 08 '20 at 09:34
  • Does this answer your question? [Why does jQuery or a DOM method such as getElementById not find the element?](https://stackoverflow.com/questions/14028959/why-does-jquery-or-a-dom-method-such-as-getelementbyid-not-find-the-element) – TylerH Dec 30 '22 at 16:23

1 Answers1

0

this.setState is an async function so by the time you get the value from the state this.state.txReceipt is not guaranteed exist.

I'll fix your code to this, pls tell if it works or not:

try {
  this.setState({
    blockNumber: "waiting..",
    gasUsed: "waiting.."
  });

  // get Transaction Receipt in console on click
  // See: https://web3js.readthedocs.io/en/1.0/web3-eth.html#gettransactionreceipt
  await web3.eth.getTransactionReceipt(
    this.state.transactionHash,
    (err, txReceipt) => {
      console.log(err, txReceipt);
      if (txReceipt) {
        this.setState({
          blockNumber: txReceipt.blockNumber,
          gasUsed: txReceipt.gasUsed
        });
      }
    }
  ); //await for getTransactionReceipt
} catch (error) {
  //try
  console.log(error);
} //catch
vuongvu
  • 811
  • 6
  • 15