How to work with Moralis (> 1.x) from React?

There’s some code in the documention and at github, but it no longer works.

For instance:

import React, { useEffect, useState, useMemo } from "react";
import { useMoralis } from "react-moralis";
import MoralisDappContext from "./context";

function MoralisDappProvider({ children }) {
  const { Moralis, user, web3, enableWeb3, isWeb3Enabled } = useMoralis();
  // const web3Provider = /*await*/ Moralis.enableWeb3();  //needed at all?


  useEffect(() => {
    Moralis.onChainChanged(function (chain) {
      setChainId(chain);
    });

    Moralis.onAccountChanged(function (address) {
      setWalletAddress(address[0]);
    });
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);


  // doesn't work
  useEffect(() => setChainId(web3.givenProvider?.chainId)); // "givenProvider" doesn't exist


  //.....

Not to mention that there’s no code as a whole, but there’re only pieces of code: one here, other there… and some don’t work. How to glue them, after all?

The givenProvider? property doesn’t even exist.

Is there code that works?


also, await can’t be used in React components. How to call Moralis functions that requireawait inside a component then? In the context of Moralis. For instance, enableWeb3()

also, await can’t be used in React components. How to call Moralis functions that requireawait inside a component then? In the context of Moralis. For instance, enableWeb3()

You run await code in an async function defined either inside or outside your component. And then call that function as normal.

enableWeb3 doesn’t require await according to the docs.

What are you looking to do?

Will be great if you can drop a reference to the mentioned instances

What are you looking to find out?
Implement a sub-task of a large task.

Have you looked over the docs here? https://github.com/MoralisWeb3/react-moralis

E.g. there is no mention of givenProvider. Try using chainId from the useMoralis hook.

I’ve looked at that. Show me what it is what’s supposed to help me there.

givenProvider exists in the very github, in one of the repositories, of Moralis

In that example, there is a fallback when givenProvider doesn’t exist so that’s ok. Try using chainId from the useMoralis hook.