[react-moralis] problems using web3 with useMoralis hook

Hey :wave:
I’ve set up react-moralis and authentication is working fine + I can enable web3 after a user is logged in but the web3 object i get from calling const { web3 } = useMoralis() appears to be the global web3 rather than the Moralis.Web3 class.

For example:

import React from 'react';
import { useMoralis } from "react-moralis";


const App = () => {
  const { web3, enableWeb3, isWeb3Enabled, authenticate, isAuthenticated, user } = useMoralis();


  if (!isAuthenticated) {
    return (
      <div>
        <button onClick={() => authenticate()}>Authenticate</button>
      </div>
    );
  }

  const getTokens = async () => {
    const tokens = web3.getTokenBalances();
    console.log(tokens); // I get an error "web3.getTokenBalances is not a function"
  }

  return (
    <div>
      <h1>Welcome {user.get("username")}</h1>
      {isWeb3Enabled ? (
        <button onClick={() => getTokens()}>
          GET TOKENS
        </button>
      ): (
        <button onClick = { () => enableWeb3() }>
          ENABLE WEB3
        </button>
      )}
    </div>
  );
}

export default App;

1 Like

Hi, it is correct that it is returning the web3 instance, to get access to the web3 provider etc, not the whole Moralis.Web3 class. We might revisit that in the future. I agree that it should be easier to use all other web3 functionalities in Moralis.

For now, you do have access to the whole Web3 class via:

const { Moralis } = useMoralis()

(or alternatively, you could import Moralis via import { Moralis } from 'moralis})

Note that we are improving the helper functions in a big way at the moment, and getTokenBalances will be renamed to getAllERC20. So be aware of that if you are running the latest version.

2 Likes

What is best way to get all ERC 20 (getAllERC20 ?) in react-moralis ?

const { authenticate, isAuthenticated, user, Moralis, ...rest } = useMoralis();
Moralis.Web3.getAllERC20()
@deprecated — use the functions from Moralis.Web3API instead

You’ll have to use account.getTokenBalances from we3api.

1 Like