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 };