mdtanrikulu/use-metamask

'Component is not mounted' error when calling connect() from an onClick handler

GAlcaraz opened this issue · 2 comments

EDIT: Seems to be an issue with React 18. Possible workaround would be to remove the Reac.StricMode component wrapping the app (not recommended).

Hi. I'm getting the following error when calling the connect() function from anything other than the initial useEffect hook:
image

I tested this just using an out-of-the-box create-react-app, so I'm not sure what's going on. Seems something really simple to need to add a workaround. Using React 18.2.

import logo from "./logo.svg";
import "./App.css";
import { useMetamask } from "use-metamask";
import { ethers } from "ethers";

function App() {
  const { connect } = useMetamask();

  return (
    <div className="App">
      <header className="App-header">
        <img src={logo} className="App-logo" alt="logo" />
        <p>
          Edit <code>src/App.js</code> and save to reload.
        </p>
        <button
          onClick={async () => {
            await connect(ethers.providers.Web3Provider, "any");
          }}
        >
          Click me!
        </button>
        <a
          className="App-link"
          href="https://reactjs.org"
          target="_blank"
          rel="noopener noreferrer"
        >
          Learn React
        </a>
      </header>
    </div>
  );
}

export default App;
import React from "react";
import ReactDOM from "react-dom/client";
import "./index.css";
import App from "./App";
import { MetamaskStateProvider } from "use-metamask";

import reportWebVitals from "./reportWebVitals";

const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(
  <React.StrictMode>
    <MetamaskStateProvider>
      <App />
    </MetamaskStateProvider>
  </React.StrictMode>
);

Reason was React 18's new design over use-strict, here is some more context.

Gonna make a patch to make it work.

I was making a fix for that but after some research I decided to leave this as it is. Cuz the fix will be temporary and hacky just for react 18, for later versions this fix may be not enough and create other side effects. the best approach is removing the stict mode from the dev code unfortunately. In production everything will work as expected.