简体   繁体   中英

Line Chart data not showing

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:

网页+控制台

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;

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))
}, []);

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