Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

161
Vistas
Save mouse position in a state with react

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.

almost 4 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

0

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 }]);
};
almost 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda