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

105
Vistas
useEffect doesn't see updated array

Below is my code snippet that doesn't work as intended. The thing is the first console.log in upper useEffect shows that in fact the array has length 1 and it contains an item BUT it doesn't pass the if check. I assume that console.log is somehow asynchronous and it sees the updated state but the if doesn't. In that case I'm not sure how would I wait for the state to update because I thought that useEffect REACTS ON updated stated. Thank you in advance.

const [roomsCurrent, setRoomsCurrent] = useState([]);

useEffect(() => {

    console.log(roomsCurrent);

    if (roomsCurrent.length != 0) {
        console.log(roomsCurrent.length);
    }

}, [roomsCurrent]);

useEffect(async () => {
    let roomData = [];

    if (rooms != null) {

        await Promise.all(rooms['rooms'].map(async (room) => {
            let result = await fetchRoomCurrent(room['room_identifier']);
            roomData.push({
                "room_identifier": room["room_identifier"],
                "display_name": room["display_name"],
                "temperature": result["temperature"],
                "humidity": result["humidity"],
                "pressure": result["pressure"],
                "thermostat_state": result["thermostat_state"],
                "dryer_state": result["dryer_state"]
            });
        })).then(setRoomsCurrent(roomData));
    }

}, [rooms]);

EDIT: rooms obj

{
"rooms": [
    {
        "display_name": "Living room",
        "room_identifier": "living_room"
    },
    {
        "display_name": "Bathroom",
        "room_identifier": "bathroom"
    },
    {
        "display_name": "Kitchen",
        "room_identifier": "kitchen"
    }
]
}

EDIT: Changed original code, still no luck. Not sure how to loop asynchronously through all the rooms and update after all the cycles have passed.

about 4 years ago · Juan Pablo Isaza
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