Reputation: 3
I use axios for API queries and NumberFromat to change the decimal number. Here is the App.js:
import React, { Component } from 'react';
import './App.css';
import axios from 'axios';
import web3 from "./web3";
import NumberFormat from 'react-number-format';
export default class PersonList extends React.Component {
state = {
balance: '',
bn: '',
persons: []
};
async componentDidMount() {
const balance = await web3.eth.getBalance("0x2f6aA9e80385316eEe006AB8bB7943abF333A063") / 1e18;
const bn = financial(balance);
const axios = require('axios');
function financial(x) {
return Number.parseFloat(x).toFixed(2);
};
axios.get(`https://api.coinmarketcap.com/v1/ticker/ethereum/?convert=USD`)
.then(res => {
const persons = res.data;
this.setState({ persons });
})
this.setState({ balance, bn });
};
render() {
return (
<div>
<p>
{this.state.persons.map(person => <p>"portfolioValue": {this.state.bn}, "usdeth": {person.price_usd}</p>)}
</p>
</div>
);
}
}
It's displayed as
"portfolioValue": 0.06, "usdeth": 93.270616772
So, I need to change the number of decimals of the second value like so 93.27. Looks like the easy task, but I stuck with it.
Upvotes: 0
Views: 16758
Reputation: 7591
you should use below mentioned code.
render() {
return (
<div>
<p>
{this.state.persons.map(person =>
<p>"portfolioValue": {this.state.bn}, "usdeth": {this.financial(person.price_usd)}</p>)
}
</p>
</div>
);
}
Upvotes: 0
Reputation: 1838
You had some problems:
require('axios')
at the top file, not in componentDidMount
, that will be good performance. Edit: you've import, so don't need require it againfinancial
should be an utility, that mean it is useful, should be declared in class, not in function componentDidMount
.person.price_usd
, you don't use financial
, so it's not working.This is solution
import React from 'react';
import './App.css';
import axios from 'axios';
import web3 from "./web3";
// useless library
// import NumberFormat from 'react-number-format';
// Require Axios here for better performance
// const axios = require('axios');
export default class PersonList extends React.Component {
state = {
balance: '',
bn: '',
persons: []
};
// place here for best utilities
financial = (x) => Number.parseFloat(x).toFixed(2);
async componentDidMount() {
const balance = await web3.eth.getBalance("0x2f6aA9e80385316eEe006AB8bB7943abF333A063") / 1e18;
const bn = this.financial(balance);
axios.get(`https://api.coinmarketcap.com/v1/ticker/ethereum/?convert=USD`)
.then(res => {
const persons = res.data;
this.setState({ persons });
})
this.setState({ balance, bn });
};
render() {
return (
<div>
<p>
{this.state.persons.map(person =>
<p>"portfolioValue": {this.state.bn}, "usdeth": {this.financial(person.price_usd)}</p>)
}
</p>
</div>
);
}
}
Upvotes: 1