I am trying to generate a scatterplot using chartJS. The plot wont graph.
When i feed in data manually by declaring the data, it works fine,
var scatter = [
{ x: 65, y: 75 },
{ x: 59, y: 49 },
{ x: 80, y: 90 },
{ x: 81, y: 29 },
{ x: 56, y: 36 },
{ x: 55, y: 25 },
{ x: 40, y: 18 },
]
but when I get the data via an API call and push the data to the array, it won't work. Any suggestions? I suspect its to do with how data is pushed onto the array but not sure what's wrong.
Thank you
Minimum solution below
import React, { useEffect, useState } from 'react';
import axios from 'axios';
function App() {
const [scatterData, setScatterData] = useState({});
const chart = () => {
var scatter = [];
axios.get('http://dummy.restapiexample.com/api/v1/employees')
.then(res => {
let temp = res.data.data
temp.forEach( i=> {
let age = parseInt(i.employee_age)
let salary = parseInt(i.employee_salary)
scatter.push({"x": age,
"y": salary})
})
}).catch(err => {
console.log(err)
})
console.log(scatter)
setScatterData({
datasets: [
{
label: 'test',
fill: true,
backgroundColor: 'rgba(75,192,192,0.4)',
pointBorderColor: 'rgba(75,192,192,1)',
pointBackgroundColor: '#fff',
pointBorderWidth: 1,
pointHoverRadius: 10,
pointHoverBackgroundColor: 'rgba(75,192,192,1)',
pointHoverBorderColor: 'rgba(220,220,220,1)',
pointHoverBorderWidth: 2,
pointRadius: 3,
pointHitRadius: 10,
data: scatter,
backgroundColor: [
'rgba(75,192,192,0.6)'
],
borderWidth: 4
}
]
});
}
useEffect(() ={
chart()
},[])
return (
<div className ="container-fluid">
<div class="row">
<div className ="col-md-12">
<Scatter data={scatterData}/>
</div>
</div>
</div>
)
};