diff --git a/esphome/components/api/api_server.cpp b/esphome/components/api/api_server.cpp index c061cb209b..5503cf4db8 100644 --- a/esphome/components/api/api_server.cpp +++ b/esphome/components/api/api_server.cpp @@ -148,16 +148,14 @@ void APIServer::loop() { while (client_index < this->clients_.size()) { auto &client = this->clients_[client_index]; - if (!client->flags_.remove) { + if (client->flags_.remove) { + // Rare case: handle disconnection (don't increment - swapped element needs processing) + this->remove_client_(client_index); + } else { // Common case: process active client client->loop(); client_index++; - continue; } - - // Rare case: handle disconnection - this->remove_client_(client_index); - // Don't increment client_index since we need to process the swapped element } }