[SOLVED] Issue with Use Moralis

I am getting below errors :

Uncaught (in promise) Error: You need to call Moralis.start with an applicationId before using Moralis.

Uncaught NoMoralisContextProviderError: Make sure to only call useMoralis within a

What can i do to resolve these?

useMoralis hook provides a isInitialized boolean state which can be used to check if Moralis is started successfully or not.

const { isInitialized } = useMoralis();

If you know which part of the code is causing the error then you can create a if condition to check if isInitialized is true before running that code.

Where should it be done exactly?
Below is my code format exactly.

Can you share your code again? I can’t see your code in the post.

>  <MoralisProvider appId={APP_ID} serverUrl={SERVER_URL}>
>         <MoralisDappProvider >
>           <Provider store={store}>
>             <Router>
>               <App isServerInfo />
>             </Router>
>           </Provider>
>         </MoralisDappProvider>
>       </MoralisProvider>

> Blockquote

I have created MoralisDappProvider which uses react-moralis to get chain, isInitialized, web3 etc,
check further to switchNetwork, checkIfWalletIsConnected

I am trying to create a colelction but got the above mentioned errors.

MoralisDappProvider.ts

import React, { useEffect, useState } from "react";
import { useMoralis } from "react-moralis";
import MoralisDappContext from "./context";
import { MARKET_ADDRESS } from "config/constant";

const MORALIS_API_KEY = process.env.REACT_APP_MORALIS_SERVER_URL;
function MoralisDappProvider({ children }) {
  let { enableWeb3, Moralis, user, web3, account, isInitialized} = useMoralis();

  const [walletAddress, setWalletAddress] = useState();
  const [chainId, setChainId] = useState();
  const [installedMetaMask, setInstalledMetaMask] = useState(true);
  const [contractABI, setContractABI] = useState(
    '[ { "inputs": [ { "internalType": "address", "name": "nftContract", "type": "address" }]}]'

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

  Moralis.start({ serverUrl, appId});

  async function initializeApp() {
  let currentUser = Moralis.User.current();
  if (!currentUser) {
    currentUser = await Moralis.Web3.authenticate();
  }
  }

  initializeApp();

  const [marketAddress, setMarketAddress] = useState(MARKET_ADDRESS);
  const NODE_URI =
    process.env.NODE_ENV === "development"
      ? process.env.REACT_APP_DEV_API_URI
      : process.env.REACT_APP_API_URL;

  useEffect(async () => {
    web3 = await enableWeb3();
    console.dir(`Web3 : ${web3} ${Object.keys(web3)} ${web3} ${web3.givenProvider}`)
    setChainId(web3?.chainId);
  }, [isInitialized]);

  useEffect(() => {
    Moralis.onChainChanged(function (chain) {
      setChainId(chain);
    });

    setWalletAddress(account)
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

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

  useEffect(() => {
    if (!window.ethereum) {
      setInstalledMetaMask(false);
    }
  });

  return (
    <MoralisDappContext.Provider
      value={{
        walletAddress,
        chainId,
        marketAddress,
        setMarketAddress,
        contractABI,
        setContractABI,
        installedMetaMask,
        NODE_URI,
      }}
    >
      {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 };

Do you know which line is causing the error? You basically need to add an if condition to check before using Moralis web3api/server functions.

if(isInitialized){
// Your code
}

We are trying to create-collection
similarly we have multiple APIs for the Morlais operation
Should I test it using isInitialized everytime?

You can use it once enclosing a component in it.

if(isInitialized){
return (
// your components which need to be
// render only when Moralis is successful initailized
)
}

// or 

if(isInitialized){
// your components which need to be
// render only when Moralis is successful initailized
}

We just have to control when the component should get rendered.
And this is only required if you have a component using Morais API as soon as it gets rendered.

isInitialized is coming to be true anyway which does not make any difference
but for create-collection / mint-nft / list-collection
its not going to moralis?

Are you still seeing the same error after using isInitialized ?

John, isInitialized is true
Which makes all our components renderable any which way.
I have tried rendering few components using isInitialized as well but nothing changed.

Error received :
MoralisWeb3.js:1869 Uncaught (in promise) Error: Missing web3 instance, make sure to call Moralis.enableWeb3() or Moralis.authenticate()

Do you know which part of the code is causing this error?

We should be able to fix it by running enableWeb3 or by using isWeb3Enabled to check if web3 is enabled before rendering the component which is causing this error

I am checking the same.
One question though

If one of my API is hitting Moralis server and then depending on same data received from Moralis API
It hit a backend server connected to Mongo Database.
Where is call exactly going to?
Self Hosted Server (replica of Moralis set up node)

When we make a call in frontend, react moralis internally calls the the cloud function defined in the self hosted server.

You can find all the cloud code in this folder path.
parse-server-migration/src/cloud

Only database is connected to mongo db and the cloud code will be available on server itself.

If a function is
calling an Moralis API to retrieve list of NFTs
and get the count and on basis of that count, we store some details in MongoDB

call is going from my FE to my deployed self hosted server and from there to MongoDB
Is it?

@johnversus Can we connect on short google meet?
I am stuck with issue mentioned in self hosting?

Yes, that is how it is. The mongodb database url which we saved in .env file when setting up server will be used to save data in mongo db. We don’t have to write any extra code for it. It will handled internally by the parse server config.

You can save data to database with the same code used for moralis db

Additionally you can also setup parse dashboard to visually see the data that is getting stored in mongo db.

You can contact me in discord at JohnVersus#1595, but I think it is better to share on forum if I don’t know the answer others can also check.