8.6 - Bitcoin API Completed Code
Bitcoin.js
import React, { Component } from 'react';
import LineChart from './LineChart';
import InfoBox from './InfoBox';
export default class Bitcoin extends Component {
constructor() {
super();
this.state = {
fetchingData: true,
data: [],
}
}
componentDidMount() {
const url = 'https://api.coindesk.com/v1/bpi/historical/close.json';
fetch(url)
.then(response => response.json())
.then(bitcoinData => {
console.log(bitcoinData.bpi);
this.setState({
data: bitcoinData.bpi,
fetchingData: false
})
})
.catch(e => {
console.log(e);
})
}
render() {
return (
<div className='main'>
<div className='mainDiv'>
<h1>30 Day Bitcoin Price Chart</h1>
{ !this.state.fetchingData ? <InfoBox data={ this.state.data }/> : null }
{ !this.state.fetchingData ? <LineChart data={ this.state.data }/> : null }
</div>
</div>
);
}
};
LineChart.js
import React, { Component } from 'react';
import Chart from 'chart.js';
import moment from 'moment';
export default class LineChart extends Component {
constructor(props) {
super(props);
this.state ={
dates: [],
payout: []
}
}
componentDidMount() {
const unsortedData = this.props.data;
let dates = [];
let payout = [];
for (let item in unsortedData) {
let bitcoinDates = moment(item).format('MMM DD');
dates.push(bitcoinDates)
payout.push(unsortedData[item])
}
this.setState({
dates: dates,
payout: payout
})
}
componentDidMount() {
var chartContext = document.getElementById('myChart').getContext('2d');
var myChart = new Chart(chartContext, {
type: 'line',
data: {
labels: this.state.dates,
datasets: [{
data: this.state.payout,
backgroundColor: '#d9514e80',
borderColor: '#d9514e',
borderWidth: 2
}]
},
options: {
legend: {
display: false
},
scales: {
yAxis: [{
ticks: {
beginAtZero: true
}
}]
}
}
});
}
render() {
return (
<canvas id='myChart'></canvas>
);
}
};
InfoBox.js
import React, { Component } from 'react';
import styled from 'styled-components';
const InfoCard = styled.div `
display: inline-block;
width: 50%;
margin-bottom: 1em;
text-align: center;
color: #d9514e;
`
export default class InfoBox extends Component {
constructor(props) {
super(props);
this.state ={
payout: [],
infoCurrent: [],
infoPayout: []
}
}
componentDidMount() {
const infoData = this.props.data;
let payout = [];
for (let thing in infoData) {
payout.push(infoData[thing])
}
this.setState({
payout: payout,
infoCurrent: payout[30].toLocaleString('us-EN', { style: 'currency', currency: 'USD' }),
infoPayout: (payout[30] - payout[0]).toLocaleString('us-EN', { style: 'currency', currency: 'USD' })
})
}
render() {
return (
<div>
<InfoCard>
<div>
<h3>Current Price:</h3>
</div>
<div>
<h5>{this.state.infoCurrent}</h5>
</div>
</InfoCard>
<InfoCard>
<div>
<h3>Change Since Last Month (USD):</h3>
</div>
<div>
<h5>{ this.state.infoPayout }</h5>
</div>
</InfoCard>
</div>
);
}
};
Last updated