fetch bitcoin's historical price and draw a graph in javascript

To fetch bitcoin's historical price and draw a graph, you need to make use of an API that provides historical price data, such as the Coinbase API. Here is a step-by-step guide to fetch the data using fetch API and draw a graph using Chart.js:

  1. First, fetch the historical price data using the Coinbase API in a function called fetchBitcoinData(). The API allows you to specify the time period and granularity for the historical data.
index.tsx
const fetchBitcoinData = async () => {
  const response = await fetch(
    'https://api.coinbase.com/v2/prices/BTC-USD/historic?period=year',
  );
  const data = await response.json();
  return data.data;
};
208 chars
8 lines
  1. Then, initialize a variable to store the fetched data and call the fetchBitcoinData() function.
index.tsx
let bitcoinData;
fetchBitcoinData().then((data) => {
  bitcoinData = data;
});
79 chars
5 lines
  1. Once you have the data, you can use Chart.js to draw a graph with the historical bitcoin price data. Make sure to include the Chart.js library in your HTML file.
<head>
  <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
</head>
79 chars
4 lines
index.tsx
const chartData = {
  labels: [],
  datasets: [
    {
      label: 'Bitcoin Price',
      data: [],
    },
  ],
};

bitcoinData.forEach((priceData) => {
  chartData.labels.push(priceData.time);
  chartData.datasets[0].data.push(priceData.price);
});

const ctx = document.getElementById('bitcoinChart').getContext('2d');
const bitcoinChart = new Chart(ctx, {
  type: 'line',
  data: chartData,
});
398 chars
21 lines
  1. Finally, create a canvas element in HTML to display the chart.
<body>
  <canvas id="bitcoinChart"></canvas>
</body>
53 chars
4 lines

By following these steps, you should be able to fetch bitcoin's historical price and draw a chart to display the data.

gistlibby LogSnag