ReferenceError: Moralis is not defined

I am trying to use the live query functions, specifically the create event handler here: https://docs.moralis.io/moralis-dapp/database/live-queries#tutorial

However, I am getting a referrence error stating that Moralis is not defined.
I have already passed my app id and server url accordingly (verified that it works on my index.js).

_app.js code:

import { MoralisProvider } from "react-moralis";
import "../styles/globals.css";
function MyApp({ Component, pageProps }) {
  return (
    <div>
      <p>Hello World</p>
      <MoralisProvider
        appId={process.env.NEXT_PUBLIC_APP_ID}
        serverUrl={process.env.NEXT_PUBLIC_SERVER_URL}
      >
        <Component {...pageProps} />
      </MoralisProvider>
    </div>
  );
}
export default MyApp;

monster.js page that is causing the error:

function Monster() {
  const { save } = useNewMoralisObject("Monster");

  const [val, setVal] = useState();
  const getAnswer = async () => {
    let query = new Moralis.Query("Monster");
    let subscription = await query.subscribe();
    subscription.on("create", (object) => {
      console.log("object created");
      console.log(object);
      setVal("hi");
    });
  };
  useEffect(() => {
    getAnswer();
  }, []);

  const saveObject = async () => {
    const data = {
      strength: 1100,
      ownerName: "monsterhunter",
      canFly: true,
    };

    save(data, {
      onSuccess: (monster) => {
        // Execute any logic that should take place after the object is saved.
        alert("New object created with objectId: " + monster.id);
      },
      onError: (error) => {
        // Execute any logic that should take place if the save fails.
        // error is a Moralis.Error with an error code and message.
        alert("Failed to create new object, with error code: " + error.message);
      },
    });
  };

  return (
    <div>
      <button onClick={saveObject}>Call The Code</button>
      <p>{val}</p>
    </div>
  );
}

export default Monster;

You can import Moralis from useMoralis in your Monster component:

const { Moralis } = useMoralis();

Alternatively you can use useMoralisQuery from react-moralis.

1 Like

Thanks! This solved my problem.