Uncaught ReferenceError: Moralis is not defined

Hello, I’m starting to learn Moralis. Following the youtube video to transfer ERC721 tokens I’ve got this error.

Uncaught ReferenceError: Moralis is not defined.

when trying to use the Moralis boilerplate for React in the NFT balance to transfer a NFT to another address. I’m using this code in the console.

const options = {type: “erc721”,
receiver: “addres of the receiver”,
contractAddress: “My address”,
tokenId: “1”}
let result = await Moralis.transfer(options)

What I’m missing? I’m using Rinkeby

Thanks in advance and have a nice week :slight_smile:

Hey @snmedina91, are you using the ethereum boilerplate for React? also can you show the full code so can get more picture of what’s going on, thanks~

Yes, I’m using the boilerplate for React.

import React, { useState } from "react";
import { useMoralis, useNFTBalances } from "react-moralis";
import { Card, Image, Tooltip, Modal, Input, Skeleton } from "antd";
import {
  FileSearchOutlined,
  SendOutlined,
  ShoppingCartOutlined,
} from "@ant-design/icons";
import { getExplorer } from "helpers/networks";
import AddressInput from "./AddressInput";
import { useVerifyMetadata } from "hooks/useVerifyMetadata";
import { useHistory } from "react-router-dom";
import { Table } from 'react-bootstrap';


const { Meta } = Card;

const styles = {
  NFTs: {
    display: "flex",
    flexWrap: "wrap",
    WebkitBoxPack: "start",
    justifyContent: "flex-start",
    margin: "0 auto",
    maxWidth: "1000px",
    width: "100%",
    gap: "10px",
  },
};

function NFTBalance({setNFT}) {

  const { data: NFTBalances } = useNFTBalances();
  const { Moralis, chainId } = useMoralis();
  const [visible, setVisibility] = useState(false);
  const [receiverToSend, setReceiver] = useState(null);
  const [amountToSend, setAmount] = useState(null);
  const [nftToSend, setNftToSend] = useState(null);
  const [isPending, setIsPending] = useState(false);
  const { verifyMetadata } = useVerifyMetadata();
  const { push } = useHistory();

  async function transfer(nft, amount, receiver) {
    const options = {
      
      type: nft.contract_type,
      tokenId: nft.token_id,
      receiver: receiver,
      contractAddress: nft.token_address,
    };

    if (options.type === "erc1155") {
      options.amount = amount;
    }

    setIsPending(true);
    await Moralis.transfer(options)
      .then((tx) => {
        console.log(tx);
        setIsPending(false);
      })
      .catch((e) => {
        alert(e.message);
        setIsPending(false);
      });
  }

  const handleTransferClick = (nft) => {
    setNftToSend(nft);
    setVisibility(true);
  };

  const handleDetails = (nft) => {
    //setNftToSend(nft);
    //setVisibility(true);
    //console.log(nft)
    setNFT(nft)
    push(`/nft/${nft.token_id}`);
  };

  const handleChange = (e) => {
    setAmount(e.target.value);
  };

  //console.log("NFTBalances", NFTBalances);
  return (
    <>


  
      <div style={styles.NFTs}>
        <Skeleton loading={!NFTBalances?.result}>
          {NFTBalances?.result &&
            NFTBalances.result.map((nft, index) => {
              //Verify Metadata
              nft = verifyMetadata(nft);
              console.log(nft);

              return (
                
                <Card
                  hoverable
                  actions={[
                    <Tooltip title="Ver detalles">
                      <FileSearchOutlined onClick={() => handleDetails(nft)} />
                      <p>Ver detalles</p>
                    </Tooltip>,
                    <Tooltip title="Transferir NFT">
                      <ShoppingCartOutlined
                        onClick={() => handleTransferClick()}
                      />
                      <p>Transferir</p>
                    </Tooltip>,
                  ]}
                  style={{ width: 240, border: "2px solid #e7eaf3" }}
                  cover={
                    <Image
                      preview={false}
                      src={nft?.image || "error"}
                      fallback="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAMIAAADDCAYAAADQvc6UAAABRWlDQ1BJQ0MgUHJvZmlsZQAAKJFjYGASSSwoyGFhYGDIzSspCnJ3UoiIjFJgf8LAwSDCIMogwMCcmFxc4BgQ4ANUwgCjUcG3awyMIPqyLsis7PPOq3QdDFcvjV3jOD1boQVTPQrgSkktTgbSf4A4LbmgqISBgTEFyFYuLykAsTuAbJEioKOA7DkgdjqEvQHEToKwj4DVhAQ5A9k3gGyB5IxEoBmML4BsnSQk8XQkNtReEOBxcfXxUQg1Mjc0dyHgXNJBSWpFCYh2zi+oLMpMzyhRcASGUqqCZ16yno6CkYGRAQMDKMwhqj/fAIcloxgHQqxAjIHBEugw5sUIsSQpBobtQPdLciLEVJYzMPBHMDBsayhILEqEO4DxG0txmrERhM29nYGBddr//5/DGRjYNRkY/l7////39v///y4Dmn+Lg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NdtQcwJEyNmoFCJAhELNNtScABFyNiqFCBChULMNNSdAhJyNSiECRCjUbEPNCRAhZ6NSiAARCjXbUHMCRMjZqBQiQIRCzTbUnAARcjYqhQgQoVCzDTUnQIScjUohAkQo1GxDzQkQIWejUogAEQo121BzAkTI2agUIkCEQs021JwAEXI2KoUIEKFQsw01J0CEnI1KIQJEKNRsQ80JECFno1KIABEKNdtQcwJEyNmoFCJAhELNNtScABFyNiqFCBChULMNNSdAhJyNSiECRCjUbEPNCRAhZ6NSiAARCjXbUHMCRMjZqBQiQIRCzTbUnAARcjYqhQgQoVCzDTUnQIScjUohAkQo1GxDzQkQIWejUogAEQo121BzAkTI2agUIkCEQs021JwAEXI2KoUIEKFQsw01J0CEnI1KIQJEKNRsQ80JECFno1KIABEKNdtQcwJEyNmoFCJAhELNNtScABFyNiqFCBChULMNNSdAhJyNSiEC/wGgKKC4YMA4TAAAAABJRU5ErkJggg=="
                      alt=""
                      style={{ height: "300px" }}
                    />
                  }
                  key={index}
                >
                  <Meta title={nft.name} description={nft.token_address} />
                </Card>
              );
            })}
        </Skeleton>
      </div>
      <Modal
        title={`Transfer ${nftToSend?.name || "NFT"}`}
        visible={visible}
        onCancel={() => setVisibility(false)}
        onOk={() => transfer(nftToSend, amountToSend, receiverToSend)}
        confirmLoading={isPending}
        okText="Send"
      >
        <AddressInput autoFocus placeholder="Receiver" onChange={setReceiver} />
        {nftToSend && nftToSend.contract_type === "erc1155" && (
          <Input
            placeholder="amount to send"
            onChange={(e) => handleChange(e)}
          />
        )}
      </Modal>
      

    </>
  );
}

export default NFTBalance;

Should work right? Thanks for the answer.

hmmm yeah very strange, I thought if Moralis is undefined it is something like you forgot to import the Moralis object, but seems everything is okay, did you install the dependencies yet btw?

Yes, all is installed. I can see the details of the NFT, I can transfer ETH from rinkeby but not transfering NFTs. Kind of lost right now.
Thanks

hmmm can you try import Moralis from moralis library instead?

import  { Moralis } from 'moralis`;

and see how it goes

If you are using any script file and getting "Uncaught ReferenceError: x is not defined " which means ‘x’ is either a variable or a method which you are trying to use before declaring it using var keyword. This means that there is a non-existent variable referenced somewhere. This variable needs to be declared, or you need to make sure it is available in your current script or scope otherwise , it will endup throwing this ‘x’ is not defined error . This usually indicates that your library is not loaded and JavaScript does not recognize the ‘x’.

To solve this error: Load your library at the beginning of all your scripts.

There can be multiple other reasons for this issue:

  • Conflict with Other Libraries
  • Path to your library included is not correct
  • Llibrary file is corrupted
  • Working offline (when you use CDN)