How to use Web3API with react dapp

I am trying to use the Web3API but I am having trouble.

I have created an app using create-react-app, npm installed moralis and I can use the functions from useMoralis() no problem. But as soon as I try to use the API, say something like this…

const options = { chain: "eth", addresses: token };
const tokenMetadata = await Moralis.Web3API.token.getTokenMetadata(options);

I get an error like this…

Cannot read property ‘token’ of undefined

I have tried running this code on a Cloud function on the Moralis server, but I get the exact same error.

Can anyone point me to a tutorial on how to actually hook up the API within my dapp? I have watched countless tutorials but they all only show you how to use the API, not how to set it up or connect it.

I know I am supposed to add the API key to the header but I am not sure how to do this with react. I have also tried to download the API client from Moralis but the javascript version is not available.

Thank you in advance.

1 Like

Hey @serkyen

Your error message means that you have a typo error in the code.
Try to hardcode token address:

const options = { addresses: "0x...1"};
const tokenMetadata = await Moralis.Web3API.token.getTokenMetadata(options);

And double check how did you specified the variable token

Hope this will help you :man_mechanic:

I know I am supposed to add the API key to the header but I am not sure how to do this with react. I have also tried to download the API client from Moralis but the javascript version is not available.

It’s needed only when you make http request. In case of using Moralis.Web3API it’s not needed

Hi Yomoo,
Thank you for the quick response.

Ok here is the exact code I am running…

const options = { chain: "eth", address: "0xbf494f02ee3fde1f20bee6242bce2d1ed0c15e47" };
const tokenMetaData = await Moralis.Web3API.token.getTokenMetadata(options);
console.log(tokenMetaData )

Error is like this…

I have tried using both “address” and “addresses” in the options object.
Both result the same.

Oh, I’ve understood now the issue.

Please update moralis, moralis-react and moralis server

Here is what I have in packages.json…

“moralis”: “^0.0.28”,
“react-moralis”: “^0.2.0”,

I have tried changing it to 0.0.36 and running npm install…here is the error…

image

As I understand it, reac-moralis latest version is 0.2.0

Moralis sdk has to be at least 0.0.35
maybe you can uninstall and reinstall Moralis sdk

Tried npm update… didn’t work.

Tried…
npm uninstall moralis --save

then
npm install moralis --save

Still gets version 0.0.28

Ok working now.

Changed moralis version in packages.json, then ran npm update moralis --force to get past the dependency with react-moralis. For some reason react-moralis 0.2.0 does not like moralis version over 0.0.28.

The code is working now :slight_smile:

Thank you for your help

3 Likes