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