Handle web3 currently connecting

Hi, I have a useEffect in my react project which enables web3 every page load. This is so that I do not lose the web3 instance even if the user refreshes my react app.

useEffect(
        () => async () => {
          if (isAuthenticated) {
            console.log("INSIDE EFFECT AUTHENTICATED BUT NO WEB3");
            await Moralis.enableWeb3();
          }
        }
        , []
    );

However, I noticed in my console that I have

Cannot execute Moralis.enableWeb3(), as Moralis Moralis.enableWeb3() already has been called, but is not finished yet 

My question is, is there a moralis state like isAuthenticating for enable web3? Is this something I have to do manually in my react state? Or do you have any tips on how to elegantly handle this?

Thank you

I think that there are other hooks that you can use in that if, like isWeb3Enabling, you should find them all in GitHub in react Moralis repository documentation

1 Like

A better way of doing that is doing it on the wrapper component of the Project which is mostly App.js,

useEffect(() => {
    if (!isWeb3Enabled) {
        enableWeb3();
    }
}, [isWeb3Enabled]);

Then you can authenticate in another component rather and if you wish to do it in same effect, then you can have

useEffect(() => {
    if (!isWeb3Enabled) {
        enableWeb3();
    }
    if (!isAuthenticated) {
        authenticate();
    }
}, [isWeb3Enabled, isAuthenticated]);

But it’s better to have authentication with the users’ conscience with a button, that’s a better UX, but it depends in your choice

Thank you, will check these out today.

thank you. would like to confirm, on the first block of code you put, this will be in App.js, how will i reference the same web3 instance across other components?

For the 2nd one, you are right. I have a ‘Connect’ button which calls authenticate on user interaction.

I managed to find isWeb3EnableLoading in the docs, but it doesn’t seem to work. I’ve added conditions to my code like

if(!isWeb3EnableLoading)
                    web3 = await Moralis.enableWeb3();

But error still persists. anyone else familiar with this state? I am only using metamask

For react, you can have it in such way rather

const { enableWeb3 , isWeb3Enabled } = useMoralis()

You can check out Here for more.