[SOLVED] Unable to keep enableWeb3 on after page refresh

Hey guys,

I’m using the following function to connect a wallet to my website. I want web3 to be enabled even after reload, and I’m using the following code:

  export const AuthenticateModal = ({ isOpen, onClose }: AuthenticateModalProps) => {
    const { authenticate, enableWeb3, isWeb3EnableLoading, isWeb3Enabled, isAuthenticated } = useMoralis();
  
    const [authError, setAuthError] = useState<null | Error>(null);
    const [isAuthenticating, setIsAuthenticating] = useState(false);
  
    const handleAuth = async (provider: 'metamask' | 'walletconnect') => {
      setAuthError(null);
      setIsAuthenticating(true);

      await enableWeb3({ throwOnError: true, provider });
      const { account, chainId } = Moralis;

      if (!account) {
        throw new Error('Connecting to chain failed, as no connected account was found');
      }
      if (!chainId) {
        throw new Error('Connecting to chain failed, as no connected chain was found');
      }
      onClose();
    };


    useEffect(() => {
      if (typeof window == 'undefined') return;
      if (
          !isWeb3EnableLoading && !isWeb3Enabled
      ) {
          enableWeb3({ throwOnError: true});
      }
  }, [isWeb3EnableLoading, isWeb3Enabled]);

However, this keeps giving me the error:
Error: Cannot execute Moralis.enableWeb3(), as Moralis Moralis.enableWeb3() already has been called, but is not finished yet

I don’t know why this error shows, since my useEffect should only run if web3EnabledLoading is false.

I’d love to know where I’m going wrong.

Thanks!

For this you should also use isInitialized:

useEffect(() => {
    if (!isWeb3EnableLoading && !isWeb3Enabled && isInitialized) {
      enableWeb3({ throwOnError: true });
    }
}, [isWeb3EnableLoading, isWeb3Enabled, isInitialized]);
1 Like

Worked! I also had to make a few changes in other parts of the code though, since I removed the Moralis Auth feature. I basically had to replace all the isAuthenticated with isWeb3Enabled.

Also, in the useEffect dependencies, I only kept isInitialized and removed the other two, otherwise it didn’t allow me to disconnect.

Thanks!

1 Like