I need to save the mouse position in an array for an application, but the positions doesn't save in the array, it just replace it and I don't know why, someone help please. Here is the code:
const mouseXY = async e =>{
setCoords([...coords,{
x:e.clientX,
y:e.clientY
}])
}
useEffect(()=>{
let interval = null;
interval = setInterval(() => {
setTime((prevTime) => prevTime + 0.5);
}, 1000);
window.addEventListener('mousemove', mouseXY);
}
When I print I get this:
[{x: 379, y: 106}]
A single element in an Array. What I want to get would be something like this:
[{x: 379, y: 106},
{x: 379, y: 106},
{x: 379, y: 106},
{x: 379, y: 106},
{x: 379, y: 106},
{x: 379, y: 106},
{x: 379, y: 106}]
with the position of the mouse around the page.
It is because of staleState. coords was an empty array at the time that mouseXy was defined and handed to addEventListener, and it will always be an empty array.
Instead, update your setCoords call to use the callback pattern.
const mouseXY = (e) => {
setCoords((prevState) => [...prevState, { x: e.clientX, y: e.clientY }]);
};