Dravizz

Untitled

Sep 26th, 2021 (edited)
961
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import React, { useState, useEffect, useCallback } from "react";
  2. import { Line } from "react-chartjs-2";
  3.  
  4. const CryptoChart = (props) => {
  5.   const [coinChart, setCoinChart] = useState([]);
  6.   const [isLoading, setIsLoading] = useState(true);
  7.  
  8.   let dateList = [];
  9.   const getData = useCallback(async () => {
  10.     setIsLoading(true);
  11.     const res = await fetch(
  12.       `https://api.coingecko.com/api/v3/coins/${props.coin}/market_chart?vs_currency=usd&days=100&interval=daily`
  13.     );
  14.     const data = await res.json();
  15.     setCoinChart(() => {
  16.       setIsLoading(false);
  17.       return data;
  18.     });
  19.   }, [props]);
  20.  
  21.   const getDates = () => {
  22.     console.log(coinChart.market_caps[0][0]);
  23.  
  24.     for (let i = 0; i < 100; i++) {
  25.       const date_ob = new Date(coinChart.market_caps[i][0]);
  26.       const year = date_ob.getFullYear();
  27.       const month = ("0" + (date_ob.getMonth() + 1)).slice(-2);
  28.       const date = ("0" + date_ob.getDate()).slice(-2);
  29.       dateList.push(year + "-" + month + "-" + date);
  30.     }
  31.   };
  32.  
  33.   useEffect(() => {
  34.     getData();
  35.     getDates();
  36.   }, [getData]);
  37.  
  38.   const data = {
  39.     labels: dateList,
  40.     datasets: [
  41.       {
  42.         label: "Market Cap",
  43.         fill: false,
  44.         borderColor: "rgba(255, 0, 0, 0.3)",
  45.         borderWidth: 1,
  46.         pointRadius: 2,
  47.         data: coinChart.market_caps,
  48.       },
  49.       {
  50.         label: "Price",
  51.         fill: false,
  52.         borderColor: "rgba(0, 255, 0, 0.3)",
  53.         borderWidth: 1,
  54.         pointRadius: 2,
  55.         data: coinChart.prices,
  56.       },
  57.       {
  58.         label: "Total Volumes",
  59.         fill: false,
  60.         borderColor: "rgba(75,192,192,1)",
  61.         borderWidth: 2,
  62.         pointRadius: 2,
  63.         data: coinChart.total_volumes,
  64.       },
  65.     ],
  66.   };
  67.   console.log(data);
  68.  
  69.   var options = {
  70.     legend: {
  71.       position: "right",
  72.       labels: {
  73.         boxWidth: 10,
  74.       },
  75.     },
  76.     scales: {
  77.       xAxes: [
  78.         {
  79.           ticks: { display: false },
  80.         },
  81.       ],
  82.     },
  83.   };
  84.  
  85.   return (
  86.     <div>
  87.       <Line data={data} options={options} />
  88.     </div>
  89.   );
  90. };
  91.  
  92. export default CryptoChart;
  93.  
RAW Paste Data