0

first time using MetaMask web3

Async getAccounts does not return my Eth account which I see in MetaMask.

My fiddle https://jsfiddle.net/ysz11/qcv78h9z/1/

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Virtual data room</title>
</head>
<body>

  <!-- Target container -->
  <div id="app"></div>

  <!-- React library and ReactDOM -->
  <script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script>
  <script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
  <script crossorigin src="https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.8.29/browser.js"></script>
  <!-- <script src="web3.min.js"></script> -->
  <script src="https://cdn.jsdelivr.net/gh/ethereum/web3.js/dist/web3.min.js"></script>

  <script type="text/babel">

    // JSX code here. Or link to separate JavaScript file that contains JSX.

    const Web3Context = React.createContext(undefined);

    const App = () => {
      // TODO

      const web3 = React.useContext(Web3Context);

      const [accounts, setAccounts] = React.useState(["0x407d73d8a49eeb85d32cf465507dd71d507100c1"]);

      // cDM
      React.useEffect(() => {
        web3.eth.getAccounts((err, accs) => {
          if (err != null) {
            console.log(err)
          }

          console.log(accs);

          setAccounts(accs);
        });
      }, []);

      return (
        <div>
          <div>Ethereum js api version {web3.version.api}</div>

          {accounts.length} accounts:
          <ul>{accounts.map((acc, i) => (
              <li key={i}>{acc}</li>
          ))}</ul>
        </div>
      );
    }

    const AppNoMetaMask = () => {
      return (
        <div>Please install MetaMask</div>
      );
    }

    const HasMetaMask = () => {
      return (
        <div>{ (window.ethereum !== undefined) ?
                 <Web3Context.Provider value={new Web3(window.ethereum)}>
                   <App /> 
                 </Web3Context.Provider> :
                 <AppNoMetaMask /> }</div>
      );
    }

    ReactDOM.render(
      <HasMetaMask />,
      document.getElementById("app")
    )

  </script>

</body>
</html>
  • Sorry, but there is not a single async in your code! – goodvibration May 10 at 21:26
1

This was missing

     const HasMetaMask = () => {
+
+      // cDM
+      React.useEffect(() => {
+        window.ethereum.enable().then((account) => {
+          const defaultAccount = account[0];
+          web3.eth.defaultAccount = defaultAccount;
+
+          // done
+        });
+      }, []); // once
+
       return (

https://medium.com/metamask/https-medium-com-metamask-breaking-change-injecting-web3-7722797916a8

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.