[SOLVED] How to use Moralis.Unit on undefined values?

Hey guys,

I’m currently trying to convert a value in Wei to a MATIC value in my front end. I get the numbers from my database, so they are undefined at first. This stops me from using .toString. If I were able to use .toString, I would use:

const tokenValue = Moralis.Units.FromWei(balance.toString)

However, I’m not able to use this.

How can I represent a number in MATIC on my front end, assuming my database stores values in wei?

Thanks!

it looks like you have to get the balance first somehow from the database to display it in frontend, after that you can convert it

how do you get that balance?

I get the balance using Moralis Query and pass it in to a component as a prop. That’s not where the issue is. Do you know how I can convert it?

can you display it in the first place without to convert it?
what type of column is the data that contains that balance?

did you try JSON.stringify?

Yep, I can display it correctly. Everything is working correctly, the only issue is I need to get from a number like: 1000000000000000000 wei to a number in matic.

I would simply divide it, however you can’t divide by such large values in js.

try something like this:

const tokenValue = Moralis.Units.FromWei(balance) + 0

and then try to convert it to string

This gives invalid BigNumber value error.

Try to add so logging to see what happens. What is the type of the parameter

It’s saved as a string in the database (just checked, I thought it was saved as a number). However, if I try const tokenValue = Moralis.Units.FromWei(balance) I get Error: invalid BigNumber string (argument="value", value="NaN", code=INVALID_ARGUMENT, version=bignumber/5.7.0). I get the same even if I add + 0

Also, balance works if I pass it in regularly, so I don’t know why it says ‘value=NaN’ in that line.

Just got it. I used const tokenValue = Moralis.Units.FromWei(balance == undefined ? '0' : balance)

I think it takes sometime to receive the value from the database, but this works like a charm.

1 Like