Line Chart data not showing

Viewed 31

I'm trying to build a LineChart using chartjs, but I'm running through some issues with reading my data of the chart, the console.log function of dates and coin_value returns null for some reason even though the data is transferred from the server as it should. any idea what is the problem??

Here is the web page with the console right now:

web page + console

and here is my code:

import { Link } from "react-router-dom";
import { Line } from "react-chartjs-2";
import {Chart as chartjs, Title, Tooltip, LineElement, Legend, CategoryScale, LinearScale, PointElement} from "chart.js";

chartjs.register(
  Title, Tooltip, LineElement, Legend, CategoryScale, LinearScale, PointElement
)

function BitCoin() {
  const [data, setData] = React.useState(null);
  const [dates, setDates] = React.useState(null);
  const [coinValue, setCoinValue] = React.useState(null);


  React.useEffect(() => {
    fetch("http://localhost:3001/bitcoin")
      .then((res) => res.json()) 
      .then((data) => {

        const twoDimensionArr = data.message;
        setData(twoDimensionArr);               
        setDates(twoDimensionArr.map(item => item[0]));    
        setCoinValue(twoDimensionArr.map(item => item[1]));
   })
   .then(console.log(dates))
   .then(console.log(coinValue))
  }, []);

  const [chartData, setChartData] = useState({
    labels: dates,
    datasets: [{
      label: "value of BTC in ILS",
      data: coinValue,
      backgroundColor: 'gold'
    }]
  }, [data])

  return (
    <div style={{textAlign:"center", fontFamily:"Comic Sans MC", fontSize:"100"}}>
      THIS IS THE BitCoin PAGE

      <nav>
        <Link to="/"> Home </Link>
      </nav>

      <nav>
        <Link to="/coins"> Coins </Link>
      </nav>

      <Line
      data = {chartData}
      />

    </div>
  )
}

export default BitCoin;
1 Answers

Usestate does not have a dependency array that automatically updates, so your chartData does never get updates. in your fetch you need to call setChartData already with the correct values.

React.useEffect(() => {
  fetch("http://localhost:3001/bitcoin")
    .then((res) => res.json())
    .then((data) => {

      const twoDimensionArr = data.message;
      setData(twoDimensionArr);
      setDates(twoDimensionArr.map(item => item[0]));
      setCoinValue(twoDimensionArr.map(item => item[1]));
      setChartData({
        labels: twoDimensionArr.map(item => item[0]),
        datasets: [{
          label: "value of BTC in ILS",
          data: twoDimensionArr.map(item => item[1]),
          backgroundColor: 'gold'
        }]
      })
    })
    .then(console.log(dates))
    .then(console.log(coinValue))
}, []);
Related