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

111
Visualizações
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 à 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