This has proven to be a very reliable way for me to connect to WIFI. Hope it helps you.
void connectToWiFi()
{
int TryCount = 0;
while ( WiFi.status() != WL_CONNECTED )
{
TryCount++;
WiFi.disconnect();
WiFi.begin( SSID, PASSWORD );
vTaskDelay( 4000 );
if ( TryCount == 10 )
{
ESP.restart();
}
}
WiFi.onEvent( WiFiEvent );
}
Edit to add:
if ( (wifiClient.connected()) && (WiFi.status() == WL_CONNECTED) )
{
The best way to check for a valid WiFi connection.