2

I'm working on making a React frontend for my smart contract, but I'm having problems connecting it into my React code.

Here are the relevant portions of my code:

import TruffleContract from 'truffle-contract'

...

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

    // Initialize MetaMask plugin
    this.web3 = new Web3();
    const isMetaMaskEnabled = () => !!window.web3;

    if (!isMetaMaskEnabled()) {
      alert('Add the Metamask pluging to your browser to continue');
      return;
    }

    if (window.ethereum) {
      window.web3 = new Web3(window.ethereum)
      try {
        // Request account access if needed
        window.ethereum.enable().then(() => {
          console.log("Accounts now exposed")
        }).catch((error) => {
          console.log(error)
        })
      } catch(error) {
        // User denied account access
        console.log(error).then(() => {
          console.log("unable to obtain MetaMask Account")
        })
      }
    } else if (window.web3) {
      window.web3 = new Web3(window.web3.currentProvider).then(() => {
        console.log("Accounts always exposed")
      }).catch((error) => {
        console.log(error)
      })
    } else {
      console.log("Non-Ethereum browser detected. You should consider trying MetaMask!")
    }

    this.web3.eth.net.getNetworkType()
    .then(function(netID) {
      while (netID !== 'main') {
        // alert('Select Main Ethereum Network in MetaMask')
      }
    });

    this.state = {
      ...
      uAddress: '0x0'
    }

    this.users = TruffleContract(Users);
    this.users.setProvider(window.web3.currentProvider)

    this.users = this.users.bind(this)
  }

  componentDidMount() {
    this.users.deployed().then((instance) => {
      this.setState( {uAddress: instance.address} )
    })
  }

When I try to call deployed() on this.users, I'm getting the error,

TypeError: this.users.deployed is not a function

I know there have been similar questions asked, but they create a contract instance using the abi and contract address, and not using the TruffleContract method. I want to know if it's possible to get this way to work.

  • Why would you need this.users = this.users.bind(this)? – ivicaa Jan 10 at 22:28
  • I'm planning on passing it into a child component. Is this the right way to do it? – JarethRader Jan 11 at 1:51
  • @JarethRader Normally .bind() is used for functions not objects. – Ismael Jan 11 at 5:47
  • I'm not sure what I did, but it's working now. And I did remove this.users = this.users.bind(this). – JarethRader Jan 12 at 7:10

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.