I am at very beginner level and I 'm stuck on this task.
Tasks
- When the page loads, populate a dropdown menu with the results from a GET call to https://xc-countries-api.fly.dev/api/countries/
- When a country is selected from the country dropdown, populate a second dropdown with the results from a GET call to https://xc-countries-api.fly.dev/api/countries/<country_code>/states/
I can not get data from second API for states.
Thank you for your time...
import { useState, useEffect } from "react";
const CountriesStates = () => {
const [countries, setCountries] = useState([]);
const [states, setStates] = useState([]);
useEffect(() => {
fetch('https://xc-countries-api.fly.dev/api/countries/')
.then((response) => {
return response.json();
})
.then((data) => {
//console.log(data);
setCountries(data);
})
}, []);
useEffect(() => {
if(countries === 'default' || countries === '') {
setStates([]);
} else {
fetch(`https://xc-countries-api.fly.dev/api/countries/${countries}/states/`)
.then((response) => {
return response.json();
})
.then((data) => {
setStates(data);
})
}
}, [countries]);
return (
<>
<div>
<select name='countries' id='countries' style={{backgroundColor:'lightblue', borderRadius:'5px', fontSize:'1.3rem', marginRight:'3rem'}}>
{
countries.map((country) => (
<option key={country.id}>{country.name}</option>
))
}
</select>
</div>
<div>
<select name='states' id='states' style={{backgroundColor:'lightblue', borderRadius:'5px', fontSize:'1.3rem', marginRight:'3rem'}}>
{
states.map((state) => (
<option key={state.id}>{state.name}</option>
))
}
</select>
</div>
</>
);
};
export default CountriesStates;
country_code
. However, you need to use the selected country's code there. You can trycountries[0].code
to test. For example, the first country isAustralia
and its code isAU
. Then when you send a request to the URL with these parameters: xc-countries-api.fly.dev/api/countries/AU/states, it returns as you expected. Hope, it's clearcountries[0].code
yes I can see states on second dropdown. Bu I should study more to understand the logic and how to do it I guess.selectedCountry
and then set it when selecting a country from the first (countries) dropdown. Also, need to change the seconduseEffect
s dependency toselectedCountry
instead of thecountries
. Then it will be triggered whenever you changeselectedCountry
and will fetch states for the selected country. It might be a bit complicated to explain, so I will post an answer to explain better