0

I'm trying to load some data from a smart contract from within componentDidMount. Calling the contract from within here didn't seem to work as web3 provider wasn't ready, so I added an event listener for 'load' and did it in there.

However, it seems like my web3 object still is not yet ready to be called.

Here's what my code looks like:

  componentDidMount(){
    window.addEventListener('load', function() {

      if (typeof web3 !== 'undefined') {

        MyContract.methods.getValue().call(function(error, result){
          if (error) { console.log(error); }
          if (result) {
            console.log(result);
          }
        });
      }
}

I get this error upon making the contract call:

Error: Provider not set or invalid

I can confirm that logging web3.currentProvider.isMetaMask returns true right before this contract call. A bit confusing, any ideas?

** Upon further investigation, it appears that MyContract.currentProvider is not yet set at this point. So its not the web3 injection from MetaMask.

2 Answers 2

2

It's not ready so that means its asynchronous, so in your componentDidMount() you need something like this:

componentDidMount() {
  const value = await contractName.methods.getValue().call();
}

Now, when you use the await syntax that means you do have to mark the componentDidMount() as being async like so:

async componentDidMount() {
  const value = await contractName.methods.getValue().call();
}

Also, you mentioned you are loading data, so you should have a class-based component where you are initializing data from like so:

class App extends Component {
  constructor(props) {
    super(props);

    this.state = { manager: '' };
  }
0

i dont quite sure but it's not bad to test this :

async componentDidMount(){
    window.addEventListener('load', function() {
      let result ;
      if (typeof web3 !== 'undefined') {
        result = await MyContract.methods.getValue().call();
      }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.