1

I'm quite new to Web3 and Metamask and would like to ask how should I change the basic componenDidMount of the React truffle box so that it can detect and change accounts when I'm switching an account on Metamask.

Here is the code:

Class App extends Component {
    state = {
    web3: null,
    contract: undefined,
    account: null
    }
componentDidMount = async () => {
  try {
  // Get network provider and web3 instances.
  const web3 = await getWeb3();

  // Use web3 to get the user's accounts.
  const accounts = await web3.eth.getAccounts();
  // Get the contract instance.
  const networkId = await web3.eth.net.getId();
  const deployedNetwork = SupChain.networks[networkId];
  const instance = new web3.eth.Contract(SupChain.abi, deployedNetwork && 
  deployedNetwork.address);
  // Set web3, accounts, and contract to the state
  this.setState({ contract: instance, web3: web3, account: accounts[0] });
} catch (error) {
  // Catch any errors for any of the above operations.
     alert(`Failed to load web3, accounts, or contract. Check console for details.`,
  );
  console.error(error);
}
   };
}

I thanks in advance anybody that will take the time to help me.

0

Metamask fires events when the user changes account, logs out, changes the network. Start reading the official documentation to see how to implement the event listeners.

Your Answer

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

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