I'm trying to build a LineChart using chartjs, but I'm running through some issues with reading my data of the chart, It seems that the issue is my lables are null, but I am getting them as an array from dates (checked, and the array is transfered from the server just fine). I am not sure what the problem is, any idea what could have made the problems??
this is how the chart looks right now:
and I'm getting those several errors:
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(Number(twoDimensionArr.map(item => item[1])));
})
.then(console.log(data))
}, []);
const [chartData, setChartData] = useState({
lables: dates,
datasets:[
{
lable: "value of BTC in ILS",
data: coinValue,
backgroundColor:'gold'
}
]
})
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;
CodePudding user response:
You don't have a labels array, in your data object you have a datasets
key and a lables
key, this last one is wrong, it is supposed to be labels
. If you change it to that it will work:
const [chartData, setChartData] = useState({
labels: dates,
datasets: [{
label: "value of BTC in ILS",
data: coinValue,
backgroundColor: 'gold'
}]
})
Same for the lable
key in the dataset, it is supposed to be label
CodePudding user response:
You are writing the spelling of label
and labels
incorrect, it should be label
rather than lable
and labels
rather than lables
. And what other thing I would suggest is wrap you Line component in an condition, like
...other code
{ dates.length > 0 &&
<Line data = {chartData} />
}
...other code
This would simply wait for the api call and the dates
state to change.