React Init Moralis failed after upgrade V1.0.0

My code has been tested that it works well before Moralis’s update to V1.0.0. I fetch data in this way below.

step 1

export const initMoralis = async () => {
    window.web3 = await Moralis.Web3.enableWeb3()
    // console.log('web3 is enableWeb3😄')
    window.CharacterContract = new window.web3.eth.Contract(CharacterABI, CharacterAdress)

step 2

const hasContract = async () => {  // make sure character contract has been created.
  if (window?.CharacterContract == undefined) {
    await initMoralis()
    if (window?.CharacterContract == undefined) {
      return false
    } else {
      return true
    }
  } else {
    return true
  }
}

step3

const {isAuthenticated, user} = useMoralis()
async function getCharacterByIds(ids: number[]): Promise<CharacterInfo[]> {
    if (await hasContract()) {
      let account = tryToGetCurrentAccount(user)
      if (isAuthenticated && account) {
        const r = (await window.CharacterContract.methods.getCharacterByIds(ids).call()) as CharacterInfo[]
        return r
      }
    }
    return []
  }

Q :thinking: How to Init Moralia in Version 1.0.0 and fetch Data by Hooks way

Now --------------------

const [hasContract, setHasContract] = useState(false)
  const {isAuthenticated, user} = useMoralis()
  useEffect(() => {
    ;(async () => {
      //@ts-ignore
      await Moralis.enableWeb3()
      //@ts-ignore
      let web3Instance = new Web3(Moralis.provider)
      //@ts-ignore
      window.CharacterContract = new web3Instance.eth.Contract(CharacterABI, addresses.CharacterAddress)
      if (window.CharacterContract) {
        setHasContract(true)
      } else {
        console.log('no character contract')
      }
    })()
  }, [])

Hi Moralis 1.0 is not using web3 anymore - its using ethers by default

If you want to use the code like you posted above you have to import and init web3 like this:

include this script: https://cdnjs.cloudflare.com/ajax/libs/web3/1.7.0-rc.0/web3.min.js

await Moralis.enableWeb3()
window.web3 = new Web3(Moralis.provider)

instead of

window.web3 = await Moralis.Web3.enableWeb3()

I see in your React Version you already do that - do you get any errors in the console?

it worked once only … most of them are

InternalWeb3Provider.js:134 Uncaught (in promise) TypeError: Cannot read properties of null (reading 'on')
    at InternalWeb3Provider.<anonymous> (InternalWeb3Provider.js:134:1)
    at tryCatch (runtime.js:63:1)
    at Generator.invoke [as _invoke] (runtime.js:294:1)
    at Generator.next (runtime.js:119:1)
    at asyncGeneratorStep (asyncToGenerator.js:5:1)
    at _next (asyncToGenerator.js:27:1)

The problem came from init moralis definetely. I don’t know how to init moralis with web3.js in version 1.0.0~ because my code have been tested ~ and never change anything

my friend @LocoTheDev will show you how to do it :slight_smile:

we need to redo your code - it’s not done correctly :slight_smile:

You are excellent team…:rofl:

2 Likes

Hello @noberkli

Since 1.0.0 does not make use of web3 anymore and the fact you are using react and react-moralis, let me show you a better and cleaner way to execute functions of a contract.

you can import the execute function hook and make use of it and use it like this

  const { data, error, fetch, isFetching, isLoading } = useWeb3ExecuteFunction();
  
  const options = {
    abi: YOUR_ABI,
    contractAddress: CONTRACT_ADDRESS,
    functionName: FUNCTION_NAME,
    params: {
      paramName1: value1
      paramName2: value2,
    },
  }
 ...
const runFunction = () => {
     fetch({ params: options })
}

This should reduce a lot of code and work properly

2 Likes

Thanks LocoThedev I will try what you show me first.

and I found another 2 functions that make me confusion useAPIContract & useWeb3Contract, I read the docs they are similiar with call & send functions in Web.js? I am not sure.~~

useAPIContract = only for read-only contract calls - doesn’t require user to connect wallet

useWeb3Contract = can do both read and write calls - requires wallet connection if user is to use it

2 Likes

useWeb3ExecuteFunction slimiar with useWeb3Contract?

They are the same thing - we have them for the sake of backward compatibility

Please use useWeb3Contract

I think we will delete useWeb3ExecuteFunction in the future

I have researched the Moralis React ethereum-boilerplate-main.git there is no complete tutorial to teach how to use useWeb3Contract but with some code snipit.


import { useWeb3Contract } from "react-moralis"

const ShowUniswapObserveValues = () => {

  const { runContractFunction, contractResponse, error, isRunning, isLoading } = useWeb3Contract({

    abi: usdcEthPoolAbi,

    contractAddress: usdcEthPoolAddress,

    functionName: "observe",

    params: {

      secondsAgos: [0, 10],

    },

  });

  return (<div>

    {error && <ErrorMessage error={error} />}

    <button onClick={() => runContractFunction()} disabled={isLoading}>Fetch data</button>

    {contractResponse && JSON.stringify(contractResponse)}

    </pre>}

  </div>)

}

I have a solidity contract with 10 methods(send & call) . I can export 10 methods from 1 react hooks utlis. it’s easy to manage 10 functions. but how to export 10 methods with useWeb3Contract

if you were to do so you don’t need to fill the params in the useWeb3Contract input, instead put it inside the runContractFunction when calling the methods individually. Or another method will be using the hooks 10 times each for each method :raised_hands:

But how to get the status of each Call() in async way

Hello @LocoTheDev
Can you make a tutorial video about this update? It’s really hard for a newbie like me.
Thank you so much

1 Like

Hey you got any issue or error?

All have been fixed… Thank you.