Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

158
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda