• Empleos
  • Sobre nosotros
  • profesionales
    • Inicio
    • Empleos
    • Cursos y retos
  • empresas
    • Inicio
    • Publicar vacante
    • Nuestro proceso
    • Precios
    • Evaluaciones
    • Nómina
    • Blog
    • Comercial
    • Calculadora de salario

0

147
Vistas
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 3 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

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 3 years ago · Juan Pablo Isaza 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 Nuestro proceso Comercial
Legal
Términos y condiciones Política de privacidad
© 2025 PeakU Inc. All Rights Reserved.

Andres GPT

Recomiéndame algunas ofertas
Necesito ayuda