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

205
Visualizações
I can't set the state in my handler function

I'm trying to set a const of my state but it seems that don't work when a few days ago it worked.

I call the setter in a function like this:

const [activeMarker, setActiveMarker] = useState(null);

const handleActiveMarker = (marker) => {
  if (marker === activeMarker) {
     return;
  }
  setActiveMarker(marker);
  console.log(marker, '--', activeMarker)
};

That is called in

{markers.map(({ id, latitud, longitud}) => (
   <Marker
      key={id}
      position={{lat: latitud, lng: longitud}}
      onClick={() => handleActiveMarker(id) }
   />
))}

The attribute markers is an array of markers and it's printed well in my map, but when I click, in console.log of my handler I get the id of marker and null in activeMarker where it has to appear the same number.

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Remember useState is asynchronous so it will not update straight away. To get the console.log value to log your value you should add a useEffect.

    useEffect(() => {
        console.log(activeMarker)
    },[activeMarker])
about 4 years ago · Juan Pablo Isaza 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