I have an application which in the first instance shows all the countries, if the filter matches a single Country it shows all the data of that country, the question comes here, I am using a weather API which I must send the name of the country by URL country or the capital of said country of the only match of the search engine when it only shows a single country
Part of the code with problem
The part of the code where I present the problem is the following, here I make the request to the API, but Quito
only the country that the search filter shows as the only match should go, that is, that field must be dynamic, so I do not know how to do it since the only place where it would be rendered is in the first if where if the length of the search engine is equal to 1 it proceeds to render all the information of the country and the weather information should go there.
useEffect(() => {
axios.get(`https://api.openweathermap.org/data/2.5/weather?q=Quito&appid=c97566f1aafdd1d33ea80ef1a1ccfebd`)
.then(response => {
const apiResponse = response.data;
console.log(apiResponse);
setWeatherInfo(apiResponse);
}).catch(error => {
console.log(error);
});
}, []);
Here I must render the climate information of the country that the search engine shows as the only match
if (findCountry.length === 1) {
return (
/*findCountry.map(countryData => <div>
<p>find countries <input onChange={handleFindCountry}/></p>
<h1>{countryData.name}</h1>
<p>capital {countryData.capital}</p>
<p>population {countryData.population}</p>
<h2>Languages</h2>
<ul>
{countryData.languages.map(languageName => <li key={countryData.alpha2Code}>{languageName.name}</li>)}
</ul>
<img height={100} src={countryData.flag} alt={countryData.name}/>
</div>)*/
<div>
<p>find countries <input onChange={handleFindCountry}/></p>
<h1>{findCountry[0].name}</h1>
<p>capital {findCountry[0].capital}</p>
<p>population {findCountry[0].population}</p>
<h2>Languages</h2>
<ul>
{findCountry[0].languages.map(languageName => <li key={languageName.name}>{languageName.name}</li>)}
</ul>
<img height={100} src={findCountry[0].flag} alt={findCountry[0].name}/>
<h2>Weather in {findCountry[0].capital}</h2>
<strong>temperature: {weatherInfo.weather[0].icon}</strong>
</div>
);
}
Full application code
I recommend this way of doing it:
First we create a new state called
capital
with the initial value "Quito".Then we modified the function
handleFindCountry
and added a couple more things to it.Inside there will be the condition that if it is a single country found, the state is established
capital
precisely with the capital of the country.Then, we modify the
useEffect()
one that will bring the climate data of the capital.In this way, through the
${capital}
, we make the query dynamic and with[capital]
it we make it run every time the state is set.Now the weather of each capital will be displayed dynamically.
All the code would look like this:
Try it on the fork I made of your code.