Web3 is not defined / cannot read property null givenProvider

Iā€™m trying to implement this fix:

But where should I put those two lines? Also you canā€™t call await outside an async function.

If I put them on index, I get a ā€œcannot read property null givenProviderā€, on the MoralisDappProvider file.

I tried putting them in MoralisDappProvider and I get this:
" ReferenceError: Web3 is not defined "

index:

import React from "react";
import ReactDOM from "react-dom";
import App from "./App";
import { MoralisProvider } from "react-moralis";
import Moralis from "moralis";
import "./index.css";
import QuickStart from "components/QuickStart";
import { MoralisDappProvider } from "providers/MoralisDappProvider/MoralisDappProvider";
import Web3 from "web3";

const appId = process.env.REACT_APP_MORALIS_APPLICATION_ID;
const serverUrl = process.env.REACT_APP_MORALIS_SERVER_URL;


const enable = async() => {
  await Moralis.enableWeb3();
  const web3 = new Web3(Moralis.provider);
}



Moralis.start({ serverUrl, appId });

const Application = () => {
  enable();
  const isServerInfo = appId && serverUrl ? true : false;
  //Validate
  if(!appId || !serverUrl) throw new Error("Missing Moralis Application ID or Server URL. Make sure to set your .env file.");
  if (isServerInfo)
    return (
      <MoralisProvider appId={appId} serverUrl={serverUrl}>
        <MoralisDappProvider>
          <App isServerInfo />
        </MoralisDappProvider>
      </MoralisProvider>
    );
  else {
    console.log(appId);
    return (
      <div style={{ display: "flex", justifyContent: "center" }}>
        <QuickStart />
      </div>
    );
  }
};

ReactDOM.render(
  // <React.StrictMode>
  <Application />,
  // </React.StrictMode>,
  document.getElementById("root")
);

MoralisDappProvder:

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

const web3 = new Web3(Moralis.provider);

const enable = async() => {
  await Moralis.enableWeb3();
}

function MoralisDappProvider({ children }) {
  enable();
  const { Moralis, user } = useMoralis();
  const [walletAddress, setWalletAddress] = useState();
  const [chainId, setChainId] = useState();
  useEffect(() => {
    Moralis.onChainChanged(function (chain) {
      setChainId(chain);
    });

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

  // eslint-disable-next-line react-hooks/exhaustive-deps
  useEffect(() => setChainId(web3.givenProvider?.chainId));
  useEffect(
    () => setWalletAddress(web3.givenProvider?.selectedAddress || user?.get("ethAddress")),
    [web3, user]
  );

  return (
    <MoralisDappContext.Provider value={{ walletAddress, chainId }}>
      {children}
    </MoralisDappContext.Provider>
  );
}

function useMoralisDapp() {
  const context = React.useContext(MoralisDappContext);
  if (context === undefined) {
    throw new Error("useMoralisDapp must be used within a MoralisDappProvider");
  }
  return context;
}

export { MoralisDappProvider, useMoralisDapp };

I just started all over with the new template. I just hope they donā€™t keep changing it or in a few months everything will break again and my app will become unusable.

Any followup to this issue?
was following the youtube tutorial from youtube video and got the current working from this souce.
https://github.com/ethereum-boilerplate/ethereum-nft-marketplace-boilerplate
however, when i updated moralis and react-moralis to the latest version, it stops listing the NFTs and spitting up erros as above ā€œcannot read property null givenProviderā€. have no idea how to get it to work.
Any feedback is much appreciated.

That template is using old methods. This page shows you how to get a provider. GitHub - MoralisWeb3/react-moralis: Hooks and components to use Moralis in a React app

You can set static versions for your Moralis dependencies in your package.json. Updating packages always has its risks.

manage to fix the problem but not sure if its the correct way, added some few items at MoralisDappProvider.js as follows :

const { Moralis, user, isWeb3Enabled, provider } = useMoralis();

** also set the default chain as ā€œ0x1ā€ to coz for some reason, its not selecting any chains at load.
const [chainId, setChainId] = useState(ā€œ0x1ā€);

and on the web3.givenProvider part, change the to the followings :

useEffect(() => {
if(isWeb3Enabled){
setChainId(provider?.chainId);
}
});
useEffect(
() => {
if(isWeb3Enabled){
setWalletAddress(provider?.selectedAddress || user?.get(ā€œethAddressā€))
}
},
[isWeb3Enabled, user]
);

so far its is working, but when I want to view the NFTs collections of a address, it returns empty, so cheching the useNFTTokenIds.js how to get it working with the latest version of moralis and react-moralis.

what is the code that does that?
if it makes an web3api request then it only needs the parameters like chain and address

in the hooks named useNFTTokenIds.js, it seems to be working up until [email protected] with [email protected] returning all the list of NFTs when supplied the chain and address. but fails with the latest [email protected] and [email protected]. it seems to run this specific part :

const {
fetch: getNFTTokenIds,
data,
error,
isLoading,
} = useMoralisWeb3ApiCall(token.getAllTokenIds, {
chain: chainId,
address: addr,
limit: 10,
});

can you log those parameters, or look in the browser network tab to see what it was sent for address and chain?

there were changes since version 0.0.184 (that was last version using web3 by default)

you can read here more about react: https://github.com/MoralisWeb3/react-moralis

or look here for code examples (it also has react): https://docs.moralis.io/moralis-dapp/web3-api/token#getalltokenids

in particular token.getAllTokenIds should return the tokens from a specific contract and not the NFTs owned by a wallet address

manage to get listings following the example u give meā€¦not sure if its the correct way, I am a bit new with this whole react and moralis fyi and wanted to develop a dapp using moralis. based on here .
https://docs.moralis.io/moralis-dapp/web3-api/token#getalltokenids, i change the codes as follows :

removed this part of the code :

const {
fetch: getNFTTokenIds,
data,
error,
isLoading,
} = useMoralisWeb3ApiCall(token.getAllTokenIds, {
chain: chainId,
address: addr,
limit: 10,
});

and introduced the following :

const [data, setData] = useState();
const [error, setError] = useState();
const [isLoading, setLoadingState] = useState();

useEffect(async () => {
const options = {
address: addr,
chain: chainId,
limit: 10,
};

if (addr !== "explore"){
  setLoadingState(true);  
  try {
    const data = await token.getAllTokenIds(options);
    setLoadingState(false);
    setData(data);
  } catch (error) {
    setLoadingState(false);
    setError(error);
  }
}

}, [addr]);

//Changed the return call to :

return {
NFTTokenIds,
totalNFTs,
fetchSuccess,
error,
isLoading,
};

*now it works with the latest version of moralis and react-moralis fetching the all the tokens from a specific contract as mentioned.