I'm kinda new to React and I was trying to make a graph using Recharts, but I lost myself in a problem where the lines of the graph doesnt appear.
I use this code
const [ graphData, setgraphData ] = useState([])
const createMockData = () => {
let data = [];
let value = 50;
for (var i = 0; i <= 5 ; i ){
let date = new Date();
date.setHours(0,0,0,0);
date.setDate(i);
value = Math.round((Math.random() < 0.5 ? 1 : 0) * Math.random() * 10);
data.push({x: date, y: value});
}
//console.log(data);
setgraphData(data);
}
useEffect(() => {
createMockData();
});
To create a mockup data and this to present it
<LineChart width={500} height={200} data={graphData}>
<Line type="monotone" dataKey={graphData.x} stroke="var(--mainColor)" />
<XAxis dataKey={graphData.y} />
<Tooltip />
</LineChart>
And I dont know what I'm doing wrong. When I use a normal array it works fine, but I need the graph to be like 100 values.
Thank you
CodePudding user response:
There are four issues here:
You are setting
graphData.x
andgraphData.y
as keys, however these values will beundefined
.graphData
is an array and doesn't havex
ory
properties - and it wouldn't even make sense, because you are supposed to specify the property names to be used for each object, i.e."x"
and"y"
. You can see in your working graph that you had data objects with{ Time, Value }
, so the keys specified are"Time"
and"Value"
, and now you have{ x, y }
, so they should be"x"
and"y"
.You have
x
andy
reversed - you are attempting to setx
as key for theLine
andy
as key for theXAxis
, but it needs to be the other way round.You have
Date
objects in your data, which happen to "work" in the X axis because they are implicitly converted to a string, but the output will not be very readable, and it's not really a supported way of providing X axis values. It would be better to setx: date.toLocaleDateString()
instead of justx: date
in your data objects.Your mock data will currently be recreated in a tight loop ad infinitum, eating one CPU core in the process, because you put
createMockData
intouseEffect
but without specifying an empty dependencies array, so any rerender - including the one you trigger yourself inside ofcreateMockData
will create new mock data, which will cause new mock data to be created, and so on. The solution is to add an empty dependency array to specify that there are no circumstances under which the hook should run a second time.
Working sandbox here.
CodePudding user response:
There are two things you should fix to make to make it work:
- your
useEffect
should have an empty dependency array to prevent the endless re-rendering dataKey={graphData.x}
should be replaced withdataKey="x"
anddataKey={graphData.y}
should be replaced withdataKey="y"
Have a look at the sandbox link to see the working example