web3Modal give "window is not defined" error while initializing web3Modal instance
Asked Answered
S

1

6

I am using Nextjs + Reactjs + Typescript. Without typescript it's working perfectly but while using Typescript I got this error.

By the way I am using useMemo here but I have tried initializing it outside the function. In both cases, I got the same error.

Here is a code snippet that I am currently using

const INFURA_ID = process.env.REACT_APP_INFURA_ID;

const initWeb3 = (provider: any) => {
  const web3 = new Web3(provider);

  web3.eth.extend({
    methods: [
      {
        name: "chainId",
        call: "eth_chainId",
        outputFormatter: web3.utils.hexToNumber as any,
      },
    ],
  });

  return web3;
};

export function Web3UtilityProvider() {
  const [walletAddress, setWalletAddress] = useState(null);
  const { user, authDispatch } = useAuth();

  const dAppClient = useMemo(() => new DAppClient({ name: "Beacon Docs" }), []);

  const web3Modal = useMemo(() => {
    return new Web3Modal({
      // network: "mainnet", // optional
      cacheProvider: true, // optional
      providerOptions: {
        walletconnect: {
          package: WalletConnectProvider, // required
          options: {
            infuraId: INFURA_ID,
          },
        },
        // torus: {
        //   package: Torus,
        // },
        fortmatic: {
          package: Fortmatic,
          options: {
            key: process.env.REACT_APP_FORTMATIC_KEY,
          },
        },
        authereum: {
          package: Authereum,
        },
        bitski: {
          package: Bitski,
          options: {
            clientId: process.env.REACT_APP_BITSKI_CLIENT_ID,
            callbackUrl:
              window.location.href + "bitski-callback.html",
          },
        },
      },
    });
  }, []);

  const logoutOfWeb3Modal = useCallback(async () => {
    async () => {
      web3Modal.clearCachedProvider();
      setTimeout(() => {
        typeof window !== "undefined" && window.location.reload();
      }, 1);
    };
  }, [web3Modal]);

  const loadWeb3Modal = useCallback(async () => {
    const provider = await web3Modal.connect();

    if (!provider?.on) {
      return;
    }

    const web3 = initWeb3(provider);

    const accounts = await web3.eth.getAccounts();

    provider.on("close", () => {
      logoutOfWeb3Modal();
    });

    provider.on("accountsChanged", async (accounts: any) => {
      console.log("accountsChanged", accounts);
      if (!accounts || !accounts.length) {
        return;
      }
    });
  }, []);

  return (
    <Web3Context.Provider
      value={{
       logoutOfWeb3Modal,
       loadWeb3Modal
      }}
    >
      {children}
    </Web3Context.Provider>
  );
}

error png

Summerville answered 27/10, 2021 at 16:35 Comment(0)
S
2

Actually, this error was not related to js or ts; it was working with reactjs app due to CSR but in my case I was using nextjs and due to SSR that window object was not defined. So, to solve this error I simply used fallback (i.e useEffect).

Summerville answered 29/10, 2021 at 7:4 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.