Random Unhandlered runtime error Moralis.initPlugins()

The below code:

import { useMoralis, useMoralisWeb3Api } from "react-moralis";


export default function AnalyticsSales() {
  const { Moralis } = useMoralis();
  Moralis.initPlugins();

  useEffect(async () => {
    const GetTokenBalancesForAddressDto = {
      chainId: 1,
      address: "0xc9d0556c8011856098fc6c8fae638b7e338ede5a",
    };
    const covalentTokenBalances =
      await Moralis.Plugins.covalent.getTokenBalancesForAddress(
        GetTokenBalancesForAddressDto
      );
    const tokenBalances = covalentTokenBalances.data.items;
    console.log(tokenBalances);
  }, []);

Will give off errors randomly, meaning sometimes it gives this error sometimes it doesnā€™t. It seems Moralis object fails to initialize sometimes (unreliable).

Errors:

Unhandled Runtime Error
Error: You need to call Parse.initialize before using Parse.

Not even using parse so this is weird.

Unhandled Runtime Error
TypeError: Cannot read properties of undefined (reading 'covalent')

Using react with next.js, MoralisProvider is configured correctly and working (sometimes i guess).

Any ideas on how to make this more reliable and work?

You need to initialise Moralis before using it.
Moralis.start({appId, serverUrl}) is the way to go.

Isnā€™t this done only once with the provider? Works fine with the below code in a component:

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

function App() {
  const { authenticate, isAuthenticated, user } = useMoralis();

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

  return (
    <div>
      <h1>Welcome {user.get("username")}</h1>
    </div>
  );
}

Moralis.start isnā€™t mentioned a single time in the react docs???

In react you can do it without Moralis.start if you use the provider where you set server url and app id

I think that you can check if Moralis is initialized with a specific hook in react

Yes, iā€™ve done this and the problem is that itā€™s unreliable.

Works sometimes, sometimes doesnt.

@dani Moralis.start isnā€™t mentioned once in the ethereum boilerplate: https://github.com/ethereum-boilerplate/ethereum-boilerplate/search?q=Moralis.start

I can always get it to work by removing

import { useMoralis, useMoralisWeb3Api } from "react-moralis";

Refreshing

And adding

import { useMoralis, useMoralisWeb3Api } from "react-moralis";

But with just a normal refresh Moralis will lose state.

Maybe you can add an await here

Made it into await Moralis.initPlugins();
and moved it inside

 useEffect(async () => {
    await Moralis.initPlugins();
.
.
.

Same error, but i can get it to work by removing
import { useMoralis, useMoralisWeb3Api } from ā€œreact-moralisā€;
refreshing and adding it back in.

Itā€™s getting pretty frustrating