简体   繁体   中英

ChartJS with React: Only one value showing on time chart

I am creating a cryptocurrency price tracker with React. I am using axios to make API requests and get information about the price history of different cryptocurrencies. This works fine, but when I am creating the chart with ChartJS, the chart only shows one value, even though I have thousands. Anyone know how to fix this? Big thanks in advance.

Here is my code for the chart component:

import Chartjs from "chart.js";
import axios from "axios";
import { historyOptions } from "../../chartConfigs/chartConfigs";

const HistoryChart = ({ coinId }) => {
    const [timeLength, setTimeLength] = useState(30);
    const chartRef = useRef();
    const [timeSeriesData, setTimeSeriesData] = useState([]);
    
    useEffect(() => {
        const timeSeriesDataArray = [];
        axios.get(`https://api.coingecko.com/api/v3/coins/${coinId}/market_chart?vs_currency=usd&days=${30}`)
        .then(response => {
            response.data.prices.forEach(element => {
                timeSeriesDataArray.push(
                    {
                        t: element[0],
                        y: element[2].toFixed(2)
                    }
                )
            })
            setTimeSeriesData(timeSeriesDataArray)
        })
        .catch(error => console.log(error))
    }, [coinId, timeLength])

    useEffect(() => {
        if (chartRef && chartRef.current) {
            const chartInstance = new Chartjs(chartRef.current,{
                type: 'line',
                data: {
                    datasets: [{
                        label: "Price",
                        data: timeSeriesData,
                        backgroundColor: "rgba(174, 374, 194, 0.5)",
                        borderColor: "rgba(174, 374, 194, 0.4)",
                        pointRadius: 0,
                        borderWidth: 1
                    }]
                },
                options: historyOptions
            })
        }
    }, [timeSeriesData])

    return (
        <div className="history-chart-container">
            <canvas ref={chartRef} id="history-chart" width={1200} height={500}></canvas>
        </div>
    )
}

export default HistoryChart

Here is my code for the chart options (historyOptions):

    lineHeighAnnotation: {
        always: true,
        hover: false,
        lineHeight: 1.5
    },
    animation: {
        duration: 2000
    },
    maintainAspectRatio: false,
    responsive: true,
    scales: {
        xAxes: {
            type: "time",
            distribution: "linear",
        }
    }
}```


  [1]: https://i.stack.imgur.com/e7g4P.png
  [2]: https://i.stack.imgur.com/t4YIa.png

This could be fixed by changing your line chart into a scatter chart.

const chartInstance = new Chartjs(chartRef.current,{
  type: 'scatter',
  ...

To still get the lines drawn between the data points, you need to define the option showLine: true on the dataset.

datasets: [{
  label: "Price",
  showLine: true,
  ...
}]

UPDATE

You should also make sure to update the chart when new data is added and the chart already exists. Not knowing much about react.js, you could make chartInstance a global variable and proceed as follows:

if (chartRef && chartRef.current) {
   chartInstance = new Chartjs(chartRef.current,{
     type: 'line',
     ...
} else {
   chartInstance.update();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM