0

I've been trying to run the following code:

$(document).ready(function(){

  var myContract;

  function startApp() {
    myContract = new web3.eth.Contract(crowdsaleABI, 
    "0xfA6eeb8558c548B742E3745716aAEF04139a8d97");
  }

  function displayPrice() {
    myContract.methods.tokenPrice().call((err, result) => {
    console.log(web3.utils.fromWei(result, "ether"))});
  }

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

    // Checking if Web3 has been injected by the browser 
    (Mist/MetaMask)
    if (typeof web3 !== 'undefined') {
      // Use Mist/MetaMask's provider
      web3 = new Web3(web3.currentProvider);
      document.write("You are connected to MetaMask");
    } else {
      // Handle the case where the user doesn't have web3.
      document.write("You are not connected to MetaMask");
      web3 = new Web3(new 
      Web3.providers.HttpProvider("HTTP://127.0.0.1:7545"));
    }
    // Now you can start your app & access web3js freely:
    startApp();

  });

 console.log("Hello World");
 displayPrice();

});

However, I've been getting the following errors:

Uncaught TypeError: Cannot read property 'methods' of undefined
Uncaught DOMException: Failed to execute 'removeChild' on 'Node': The node to be removed is not a child

Particularly, first error is stopping me from doing any progress. I'm running web3 1.0.0-beta.34 (checked using npm ls web3).

1 Answer 1

0

Your displayDevice() call is executed before the window loads (where you call startApp()).

So myContract is not initialized yet in your displayPrice function.

Your error is telling you "myContract is undefined".

3
  • What changes would I have to implement? Sorry, still very new to coding in general.
    – dkelsen
    Jul 29, 2018 at 16:32
  • Look up what the $(document).ready and window.addEventListener('load', ...) do (and how they differ).
    – Xilis
    Jul 29, 2018 at 17:49
  • Try dropping the window.addEventListener part (keep the code inside it's callback). The problem is that displayPrice() is called before startApp(). displayPrice() uses myContract, which is initialized in startApp(). I suggest you place a couple of console logs inside the $(document).ready, the eventListener callback and so on to get a sense in what order things are being executed (keep in mind the event callback is asynchronous).
    – Xilis
    Jul 29, 2018 at 17:57

Your Answer

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

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