Unhandled Rejection (Error): Missing web3 instance, make sure to call Moralis.enable() or Moralis.authenticate()

Getting Error: Unhandled Rejection (Error): Missing web3 instance, make sure to call Moralis.enable() or Moralis.authenticate()

Using local hardhat chain, so can’t use the web3api

Wondering whats wrong with this code, new to calling functions from Moralis. Is there a different way I should be doing this?

 import React, { useEffect } from "react";
import { useMoralis, useMoralisWeb3Api } from "react-moralis";
import { HStack, Box } from "@chakra-ui/layout";
import { Image, Badge } from "@chakra-ui/react";
import { Wrap } from "@chakra-ui/react";
import NFT from "./artifacts/contracts/NFT.sol/NFT.json";
import Market from "./artifacts/contracts/Market.sol/NFTMarket.json";

// Sample card from Airbnb

function CardList({ nftaddress, chain }) {
  const {
    authenticate,
    isWeb3Enabled,
    isAuthenticated,
    isAuthenticating,
    user,
    enableWeb3,
    logout,
    authError,
    userError,
    Moralis,
    web3,
  } = useMoralis();

  const Web3Api = useMoralisWeb3Api();

  useEffect(() => {
    if (!isWeb3Enabled) {
      enableWeb3();
    }
    if (isAuthenticated) {
      loadNFTs();
    }
  }, [web3.currentProvider]);

  async function loadNFTs() {
    const contract = new web3.eth.Contract(NFT.abi, nftaddress);

    const options = {
      contractAddress: nftaddress,
      functionName: "balanceOf",
      abi: NFT.abi,
      params: { owner: user.attributes.ethAddress },
    };
    const balanceOf = await Moralis.executeFunction(options);

    console.log(balanceOf);
  }

did you try with web3 = await Moralis.enableWeb3() in that getBalance function?

also, you may have some old version of Moralis SDK maybe

I declare web3 above like this…

  const {
    authenticate,
    isWeb3Enabled,
    isAuthenticated,
    isAuthenticating,
    user,
    enableWeb3,
    logout,
    authError,
    userError,
    Moralis,
    web3,
  } = useMoralis();

and since I call web3.currentProvider in useEffect, I get chicken before the egg if move it into the function.

You were right! Thank you!

This worked:

  async function loadNFTs() {
    const web3 = await Moralis.enableWeb3();
    const options = {
      contractAddress: nftaddress,
      functionName: "balanceOf",
      abi: NFT.abi,
      params: { owner: user.attributes.ethAddress },
    };
    const balanceOf = await Moralis.executeFunction(options);

    console.log(balanceOf);
  }